How Do I Create a Pool of Background Workers?

被刻印的时光 ゝ 提交于 2020-01-23 04:13:10

问题


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!


回答1:


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

Thread/threadpool or backgroundworker




回答2:


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



来源:https://stackoverflow.com/questions/26408503/how-do-i-create-a-pool-of-background-workers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!