How to stop BackgroundWorker on Form's Closing event?

后端 未结 12 1852
春和景丽
春和景丽 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:07

    Can you not wait on the signal in the destructor of the form?

    AutoResetEvent workerDone = new AutoResetEvent();
    
    private void HandleClosingEvent(object sender, CancelEventArgs e)
    {
        this.bgWorker.CancelAsync();
    }
    
    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        while (!this.bgWorker.CancellationPending) {
            Invoke((Action) (() => { this.textBox1.Text =   
                                     Environment.TickCount.ToString(); }));
        }
    }
    
    
    private ~Form1()
    {
        workerDone.WaitOne();
    }
    
    
    void backgroundWorker1_RunWorkerCompleted( Object sender, RunWorkerCompletedEventArgs e )
    {
        workerDone.Set();
    }
    

提交回复
热议问题