Is it safe to cancel a DoWork subscription after calling RunWorkerAsync, but before the function exits?

I have many methods (they work only one at a time), they all use the same RunWorkerCompleated and ProgressChanged methods, but they all have different Dowork methods. Is it possible to do the following:

 private void button_Process_Click(object sender, EventArgs e) { bgWork_Process.DoWork += Scrub_DoWork; bgWork_Process.RunWorkerAsync(); bgWork_Process.DoWork -= Scrub_DoWork; } 

or can i make it happen? I did not see anything in the MSDN on it, saying that it is not allowed, and it so far (so far) works fine in my program, but I wanted to check here to see if anyone has problems with this.

+6
source share
1 answer

What you can do to make sure that the event handler is not deleted until you are done with it would be to do something similar to

 Action DoWorkAction; private void button_Process_Click(object sender, EventArgs e) { gbHistory.Enabled = false; gbScrub.Enabled = false; DoWorkAction = new Action(Scrub_DoWork); bgWork_Process.DoWork += DoWorkAction; bgWork_Process.RunWorkerAsync(); } 

And in what handles your completion

 private void bgWork_Process_CompletedHandler(object sender, EventArgs e) { bgWork_Process.DoWork -= DoWorkAction; } 

I really feel; it’s best to have a separate BackGroundWorkers for all your actions that you need to perform, rather than using a similar shell or shell in the class so that you can more clearly understand what you are doing.

+1
source

Source: https://habr.com/ru/post/897393/


All Articles