C# Can't close form created by Background Worker

半城伤御伤魂 提交于 2019-12-24 01:25:46

问题


My Backgroundworker loads a new "pop-up" form, but how do I terminate background worker and the newly created form?

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    BussyForm bussyForm = new BussyForm();
    bussyForm.ShowDialog();
}

This has no effect:

backgroundWorker1.Dispose();
backgroundWorker1.CancelAsync();
backgroundWorker1 = null;

回答1:


You shouldn't be showing a form from a non-UI thread. You should only have one UI thread, and it, and only it, should access all of your user interface controls. Your non-UI threads shouldn't access UI elements at all.

You should be showing the given busy popup from the UI thread instead.

Requesting cancellation from the BackgroundWorker, or disposing of it, won't close the form, or force the thread to stop executing, which is why your form stays open.

Instead just show your popup from the UI thread when you start the background worker, and have the BGW's completed event call Close on the form:

private void button1_Click(object sender, EventArgs args)
{
    BusyForm busyForm = new BusyForm();

    BackgroundWorker worker = new BackgroundWorker();
    worker.DoWork += worker_DoWork;
    worker.RunWorkerCompleted += (_, e) => { busyForm.Close(); };
    worker.RunWorkerAsync();

    busyForm.ShowDialog();
}



回答2:


CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker.CancellationPending. Your DoWork delegate that is being ran in the background must periodically check this property and handle the cancellation itself.

You call bussyForm.ShowDialog(); so you need to close this form manually.



来源:https://stackoverflow.com/questions/20500360/c-sharp-cant-close-form-created-by-background-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!