Best practice for several long methods using background worker

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

Please, help. Thanks.

+7
c # backgroundworker winforms
source share
2 answers

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

If you have one BackgroundWorker task for a long method task, you will have a lot of control over your methods. Also, as I understand it, when an instance of BackgroundWorker performs a task, it is busy with this background task and, therefore, makes it inaccessible to others. Maybe I'm wrong, but it’s the way I would do it, because the DoWork () event handler can only do what it is asked to do for this BackgroundWorker. Therefore, it seems to me impossible to perform completely different tasks for only one instance of BackgroundWorker.

Does it help?

+2
source share

In short:

Benefits in one BackgroundWorker:

  • You control the execution order for several methods. However, this is also a drawback, because if you use multiple BackgroundWorkers, you "assume" that they are executed in parallel and should not worry about order;

  • Less overhead for creating and deleting threads (if possible, use the same instance each time, but this is not always possible, depending on what starts the process. Impossible if you want this to be done simultaneously);

  • If you want to communicate between a stream, you can accumulate packet communication and do it more efficiently. Moreover, it can save you some of this message if all methods run in the same thread.

Benefits in multiple BackgroundWorkers:

  • The aforementioned parallelism;

  • Each end of the process can use a different delegate and therefore perform some other operations.

Hope this helps!

+2
source share

All Articles