How to stop BackgroundWorker on Form's Closing event?

后端 未结 12 1853
春和景丽
春和景丽 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 13:58

    One solution that works, but too complicated. The idea is to spawn the timer that will keep trying to close the form, and form will refuse to close until said bgWorker is dead.

    private void HandleClosingEvent(object sender, CancelEventArgs e) {
        if (!this.bgWorker.IsBusy) {
            // bgWorker is dead, let Closing event proceed.
            e.Cancel = false;
            return;
        }
        if (!this.bgWorker.CancellationPending) {
            // it is first call to Closing, cancel the bgWorker.
            this.bgWorker.CancelAsync();
            this.timer1.Enabled = true;
        }
        // either this is first attempt to close the form, or bgWorker isn't dead.
        e.Cancel = true;
    }
    
    private void timer1_Tick(object sender, EventArgs e) {
        Trace.WriteLine("Trying to close...");
        Close();
    }
    

提交回复
热议问题