How to stop BackgroundWorker on Form's Closing event?

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

    Firstly, the ObjectDisposedException is only one possible pitfall here. Running the OP's code has produced the following InvalidOperationException on a substantial number of occasions:

    Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

    I suppose this could be amended by starting the worker on the 'Loaded' callback rather than the constructor, but this entire ordeal can be avoided altogether if BackgroundWorker's Progress reporting mechanism is used. The following works well:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        while (!this.bgWorker.CancellationPending)
        {
            this.bgWorker.ReportProgress(Environment.TickCount);
            Thread.Sleep(1);
        }
    }
    
    private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        this.textBox1.Text = e.ProgressPercentage.ToString();
    }
    

    I kind of hijacked the percentage parameter but one can use the other overload to pass any parameter.

    It is interesting to note that removing the above sleep call clogs the UI, consumes high CPU and continually increases the memory use. I guess it has something to do with the message queue of the GUI being overloaded. However, with the sleep call intact, the CPU usage is virtually 0 and the memory usage seems fine, too. To be prudent, perhaps a higher value than 1 ms should be used? An expert opinion here would be appreciated... Update: It appears that as long as the update isn't too frequent, it should be OK: Link

    In any case, I can't foresee a scenario where the updating of the GUI has to be in intervals shorter than a couple of milliseconds (at least, in scenarios where a human is watching the GUI), so I think most of the time progress reporting would be the right choice

提交回复
热议问题