How to stop BackgroundWorker on Form's Closing event?

后端 未结 12 1849
春和景丽
春和景丽 2020-11-21 13:55

I have a form that spawns a BackgroundWorker, that should update form\'s own textbox (on main thread), hence Invoke((Action) (...)); call.
If in Handl

12条回答
  •  北海茫月
    2020-11-21 14:13

    The only deadlock-safe and exception-safe way to do this that I know is to actually cancel the FormClosing event. Set e.Cancel = true if the BGW is still running and set a flag to indicate that the user requested a close. Then check that flag in the BGW's RunWorkerCompleted event handler and call Close() if it is set.

    private bool closePending;
    
    protected override void OnFormClosing(FormClosingEventArgs e) {
        if (backgroundWorker1.IsBusy) {
            closePending = true;
            backgroundWorker1.CancelAsync();
            e.Cancel = true;
            this.Enabled = false;   // or this.Hide()
            return;
        }
        base.OnFormClosing(e);
    }
    
    void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
        if (closePending) this.Close();
        closePending = false;
        // etc...
    }
    

提交回复
热议问题