Are ThreadPool settings global or only for work items?

二次信任 提交于 2019-12-11 11:58:42

问题


If I set ThreadPool.SetMaxThreads in a WinForms application does this setting applies to only work items or for the whole assembly threads like timers and gui updates?

I'm building an application which will continuously process semi-short operations, usually around 1 minute each. I first came up with a manual thread creating version which works fine. Since I'm creating a new thread for each operation I'm looking if I can create a faster and more efficient version and I experimented with ThreadPool which didn't work better it even blocked my timer and gui updates. Is this normal or am I using it wrong?

Here's my pseude-code:

Manual Thread version: (all MaxThread and ThreadCount read and writes are done with locks)

timer1.Tick += Tick();

private void Tick()
{
    //do some text logging
    //do some TextBox updating
}

int MaxThreads = 10

while(true)
{
    if(ThreadCount < MaxThreads)
    {
        new Thread(() => Process()).Start();
        ThreadCount++;
    }
    else
    {
        Thread.Sleep(10000);
    }
}

private void Process()
{
    //do something

    ThreadCount--;
}

ThreadPool version: (the computer is dual-core Xeon on 32bit Windows server OS)

timer1.Tick += Tick();

private void Tick()
{
    //do some text logging
    //do some TextBox updating
}

ThreadPool.SetMaxThreads(10,10) **<--removing this didn't help with freezing at all**

while(true)
{
    if(ThreadPool.GetAvailableThreads() > 0)
    {
        ThreadPool.QueueWorkItem(Process, null)
    }
    else
    {
        Thread.Sleep(10000);
    }
}

private void Process()
{
    //do something
}

回答1:


According to my research on MSDN, limiting the number of ThreadPool threads will affect the following threading mechanisms:

  • ThreadPool
  • System.Threading.Timer
  • System.Timers.Timer
  • TPL Tasks

since under the hood they are using the thread pool to run their work.
The following will run on their own thread:

  • Thread
  • BackgroundWorker

The GUI timers will run on the UI thread: System.Windows.Threading.DispatcherTimer and System.Windows.Forms.Timer.




回答2:


It seems to me that either method you are using here is not the best way to achieve what you want.

It is never wise to to second guess what the optimal number of threads a threadpool should have, and there are many factors that will have a bearing on this. Something the framework and OS are far more capable of doing.

In this case, you'd probably be better off making use a Sempaphore.

In answer to your question, there is a nice article about this here.

Threadpool throttling



来源:https://stackoverflow.com/questions/11466533/are-threadpool-settings-global-or-only-for-work-items

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