Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for multiple long-methods using backgroundworker

I have a form that has many long-methods. My quest is: What is the best practice? Use anonymous method and only one backgroundworker or create an instance of BackgroundWorker to each long-method.

Please help. Thanks.

like image 782
wallybh Avatar asked Mar 10 '10 18:03

wallybh


2 Answers

I would personnaly use one instance of BackgroundWorker for each of your tasks. However, keep in mind that you may call several times the same delegate method in multiple different instances of thread.

By having one BackgroundWorker per long-method task, you will have plenty control over your methods. Furthermore, as far as my understanding goes, once an instance of a BackgroundWorker performs a task, it is busy with this background task and therefore making it unavailable for others. I may perhaps be mistaken though, but that is anyway the way I would do it, as your DoWork() event handler can do only what it is asked to do for this BackgroundWorker. So, it seems impossible to me to perform totally different tasks for only one instance of BackgroundWorker.

Does this help?

like image 94
Will Marcouiller Avatar answered Oct 15 '22 11:10

Will Marcouiller


In summary:

Advantages in one BackgroundWorker:

  1. You control the order of the execution for the multiple method. However, this is also a disadvantage, because if you use multiple BackgroundWorkers, you "assume" they are executed parallely and not have to worry about the order;

  2. Less overhead for thread creation and disposal (if possible, use same instance every time, but that's not always possible, depending on what starts the process. It's not possible if you want it to be done concurrently);

  3. If you want to communicate between thread, you can accumulate a batch communication and do it more efficiently. Moreover, it may save you some of that communication if all methods are run in the same thread.

Advantages in multiple BackgroundWorkers:

  1. The aforementioned parallelism;

  2. Each end-of-process can use another delegate and therefore do some other operation.

Hope it helps!

like image 33
Yaron Adler Avatar answered Oct 15 '22 12:10

Yaron Adler