Is it possible to reuse a backgroundworker object?

I have a refresh button that every time I click on it I want my backgroundworker object to work.

I use

if (main_news_back_worker.IsBusy != true) { // Start the asynchronous operation. main_news_back_worker.RunWorkerAsync(); } private void main_news_back_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { show_system_urls(urls); displayNewMes(newMes, newStock, newSource); displayOldMes(oldMes, oldStock); } 

The first time I use the flashlight, it works well, it also gets to RunWorkerCompleted and does its job. But the second time when I try to start the object, the is_busy property of the object is "true", and I can not start the object again ...

Do I need to create a new background worker every time I want to start it? How can I do it? Thanks.

+4
source share
2 answers

Yes, not a problem. However, you must make sure that the user cannot press the button again when BGW is busy. It is easily done by setting the Enabled property, stops the button and provides excellent visual feedback to the user. Try this for example:

  private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { System.Threading.Thread.Sleep(2000); } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { button1.Enabled = true; } 
+6
source

But the second time, when I try to run the object, the object's is_busy property is set to "true"

This means that the first background action is still in progress.

First you need to decide if you want two of these actions to continue at the same time.

If not, cancel to stop (and then restart) Bgw.

If so, create a new bgw each time.

And although you can reuse Bgw, and it makes sense in the first scenario, there is no big saving. Bgw Thread comes from ThreadPool and will still be reused.

+1
source

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


All Articles