How to stop BackgroundWorker on Form's Closing event?

后端 未结 12 1850
春和景丽
春和景丽 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();
    }
    
    0 讨论(0)
  • 2020-11-21 13:59

    I've found another way. If you have more backgroundWorkers you can make:

    List<Thread> bgWorkersThreads  = new List<Thread>();
    

    and in every backgroundWorker's DoWork method make:

    bgWorkesThreads.Add(Thread.CurrentThread);
    

    Arter that you can use:

    foreach (Thread thread in this.bgWorkersThreads) 
    {
         thread.Abort();    
    }
    

    I used this in Word Add-in in Control, which i use in CustomTaskPane. If someone close the document or application earlier then all my backgroundWorkes finishes their work, it raises some COM Exception(I don't remember exatly which).CancelAsync() doesn't work.

    But with this, I can close all threads which are used by backgroundworkers Immediately in DocumentBeforeClose event and my problem is solved.

    0 讨论(0)
  • 2020-11-21 14:00

    I'd pass in the SynchronizationContext associated with the textbox to the BackgroundWorker and use that to perform Updates on the UI thread. Using SynchronizationContext.Post, you can check if the control is disposed or disposing.

    0 讨论(0)
  • 2020-11-21 14:02

    Your backgroundworker should not use Invoke to update the textbox. It should ask the UI thread nicely to update the textbox using event ProgressChanged with the value to put in the textbox attached.

    During event Closed (or maybe event Closing), the UI thread remembers that the form is closed before it cancels the backgroundworker.

    Upon receiving the progressChanged the UI thread checks if the form is closed and only if not, it updates the textbox.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
  • 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...
    }
    
    0 讨论(0)
提交回复
热议问题