How to stop BackgroundWorker on Form's Closing event?

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

    This won't work for everyone, but if you are doing something in a BackgroundWorker periodically, like every second or every 10 seconds, (perhaps polling a server) this seems to work well to stop the process in an orderly manner and without error messages (at least so far) and is easy to follow;

     public void StopPoll()
            {
                MyBackgroundWorker.CancelAsync(); //Cancel background worker
                AutoResetEvent1.Set(); //Release delay so cancellation occurs soon
            }
    
     private void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                while (!MyBackgroundWorker.CancellationPending)
                {
                //Do some background stuff
                MyBackgroundWorker.ReportProgress(0, (object)SomeData);
                AutoResetEvent1.WaitOne(10000);
                }
        }
    

提交回复
热议问题