使用Task.Factory.StartNew新建的线程启动非常缓慢 [英] Newly created threads using Task.Factory.StartNew starts very slowly

查看:705
本文介绍了使用Task.Factory.StartNew新建的线程启动非常缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用由Task.Factory.StartNew创建的大约50-200个短时工作线程的WPF/c#应用程序中,新创建的线程开始执行需要1到10秒.

In an WPF/c# application that uses around 50-200 of short living worker-threads created by Task.Factory.StartNew it takes from 1 to 10 seconds before the newly created thread starts executing.

线程执行如此缓慢启动的原因是什么?

What is the reason for this very slow thread execution start?

更新: 延迟竟然是500毫秒

Update: The delay is excatly 500 msec

推荐答案

发现,当使用的线程池线程数超过特定值时,线程池可能不愿意每500毫秒启动一个以上的新线程.但是,使用 ThreadPool来增加MinThreads .SetMinThreads -即使不建议这样做-设置为100可以使我创建100个线程而没有500毫秒的延迟.

Found out that the thread pool can be unwilling to start more than one new thread every 500 msec when the number of thread pool threads used are over a specific value. However increasing MinThreads using ThreadPool.SetMinThreads - even though it is not recommended - to 100 enables me to create 100 threads without the 500 msec delay.

这就是帮助我的地方:

http://msdn.microsoft.com/zh-cn/library/system.threading.threadpool.setminthreads%28v=vs.100%29.aspx

https://stackoverflow.com/a/13186389/600559

这是我在App.xaml.cs(在构造函数中)结束的工作:

Here's what I ended doing in App.xaml.cs (in the constructor):

// Get thread pool information
int workerThreadsMin, completionPortThreadsMin;
ThreadPool.GetMinThreads(out workerThreadsMin, out completionPortThreadsMin);
int workerThreadsMax, completionPortThreadsMax;
ThreadPool.GetMaxThreads(out workerThreadsMax, out completionPortThreadsMax);

// Adjust min threads
ThreadPool.SetMinThreads(workerThreadsMax, completionPortThreadsMin);

这篇关于使用Task.Factory.StartNew新建的线程启动非常缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆