How to stop BackgroundWorker on Form's Closing event?

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

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

    List bgWorkersThreads  = new List();
    

    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.

提交回复
热议问题