C#线程池 - 线程的数量限制 [英] c# Threadpool - limit number of threads
本文介绍了C#线程池 - 线程的数量限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我开发一个控制台应用程序。
I am developing a console app.
我想使用一个线程池来执行网络下载。下面是一些假的代码。
I want to use a Threadpool to perform web downloads. Here is some fake code.
for (int loop=0; loop< 100; loop++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(GetPage), pageList[loop]);
}
snip
private static void GetPage(object o)
{
//get the page
}
如何阻止我的代码启动两个以上(或十年,或其他)并发线程?
How do I prevent my code from starting more than two (or ten, or whatever) simultaneous threads?
我曾尝试
ThreadPool.SetMaxThreads(1, 0);
ThreadPool.SetMinThreads(1, 0);
但他们似乎没有影响。
But they seem to have no impact.
推荐答案
我会使用的Parallel.For
并设置 MaxDegreeOfParallelism
。
Parallel.For(0, 1000, new ParallelOptions { MaxDegreeOfParallelism = 10 },
i =>
{
GetPage(pageList[i]);
});
这篇关于C#线程池 - 线程的数量限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文