我制作了一个小应用程序,其中Form是线程化的(使用BackgroundWorker),当我想退出时,以这种形式,我在QuitApplication类中调用了Program函数。
DoWork看起来像这样:

static void guiThread_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    while (true)
    {
        if (worker.CancellationPending == true)
        {
            e.Cancel = true;
            break;
        }

        if (Program.instance.form != null)
        {
            Program.instance.form.UpdateStatus(Program.instance.statusText, Program.instance.statusProgress);
        }

        Thread.Sleep(GUI_THREAD_UPDATE_TIME);
    }
}

在Form1类中,我将此方法附加到关闭窗口:
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    Program.instance.SetStatus("Closing down...", 0);

    Program.QuitApplication();
}

因此,我要确保在我按窗口上的X时一切都退出。但是,if( worker.CancellationPending == true )从未命中...这为什么呢?

QuitApplication看起来像这样:
public static void QuitApplication()
{
    Program.instance.guiThread.CancelAsync();

    Application.Exit();
}

我使用guiThread.WorkerSupportsCancellation = true

最佳答案

CancelAsync设置了CancellationPending属性,但是随后您立即退出了应用程序,而没有让后台线程有机会检测到该问题并关闭它。您需要更改UI代码以等待后台线程完成。

就个人而言,当我编写这样的应用程序时,我使窗体关闭按钮的行为就像“取消”按钮,而不是立即退出。对于最终用户而言,这要安全得多。例如:

private void abortButton_Click(object sender, EventArgs e) {
    // I would normally prompt the user here for safety.
    worker.CancelAsync();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
    if(worker.IsBusy) {
        // If we are still processing, it's not very friendly to suddenly abort without warning.
        // Convert it into a polite request instead.
        abortButton.PerformClick();
        e.Cancel = true;
    }
}

关于c# - CancelAsync是否正常工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5702965/

10-11 01:14