Search code examples
c#multithreadingbackgroundworker

How Do I Create a Pool of Background Workers?


I find that I am enjoying the simplicity of running code asynchronously through BackgroundWorkers. I have taught myself through example or trial and error on its uses, pitfalls, safe-threading etc., not so much the theory and perhaps my Achilles heel.

I have done my reserach but one thing I don't find very much talk of, how can I effectively create and use a pool of BackgroundWorkers? Or what is a better alternative that is just as simple as using BWs?

I will illustrate the problem I am running into: I had a task X, Y, and Z, each one intensive, thus it will hang up the UI thread. I decided BWs are the answer, EVEN, if this code was executed only once. I learned how to use them, some safe threading practices, and went on my way. Pretty soon my code looked like: BW1, BW2, BW3, and so forth.

Then I began to get more familiar with them and really put in code into BWs that can be used for Hardware Monitoring or other infinite looped / always running items. I still ran into a BW5, BW6.... issue.

I found creative ways to have multipurpose BackgroundWorkers by having a Global String Variable which was set before RunWorkerAsynchronous() was called and then I could either have Nested If/Elses or Switches inside the BackgroundWorker to execute the code that was needed based off of what I set the String Variable to. However, I feel I am just dancing around a limit of my self-learning.

So can anyone guide me through the concept of creating a Pool of Threads/BWs and use them as needed throughout my program, recycling the threads instead of explicitly creating each one, then having dozens of backgroundworkers for specific intensive purposes to juggle?

Note: I am not a very good programmer so I am looking for simple functional examples or explanations. Any and all help though is eagerly welcome!


Solution

  • You don't need to pool them. They use internally the ThreadPool, that is already a pool of threads.

    Thread/threadpool or backgroundworker