简体   繁体   中英

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!

I highly recommend using Tasks to achieve what you want. This manages all the hard work of selecting threads from the thread pool, balancing the threads across multiple cores etc.

if you have the function:

public void DoSomething()
{
    //things happen here
}

Then you can start tasks using:

var task = Task.Factory.StartNew(DoSomething);

or

var task = new Task(DoSomething);

You can read more at http://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx

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

Thread/threadpool or backgroundworker

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM