.net 控制线程数量
标签:最大 int lin max string rgb pre actions style
通过两种方法:
TaskFactory/ParallelOptions
class Program
{
static void Main(string[] args)
{
int num = 10;
ControlTaskNum(num);
UseParallelOptions(num);
}
///
/// 通过 ParallelOptions 控制线程数
///
///
private static void UseParallelOptions(int num)
{
List actions = new List();
for (int i = 0; i 10000; i++)
{
actions.Add(() => Console.WriteLine(i));
}
ParallelOptions parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism = num;
Parallel.Invoke(parallelOptions, actions.ToArray());
}
///
/// 通过 TaskFactory 控制线程数
///
/// 最大线程
private static void ControlTaskNum(int v)
{
TaskFactory taskFactory = new TaskFactory();
List tasks = new List();
for (int i = 0; i 10000; i++)
{
tasks.Add(taskFactory.StartNew(() => Console.WriteLine(i)));
if (tasks.Count >=v)
{
tasks.Where(t => t.IsCompleted && !t.IsCanceled && !t.IsFaulted).ToList();
Task.WaitAny(tasks.ToArray());
}
}
}
}
.net 控制线程数量
标签:最大 int lin max string rgb pre actions style
原文地址:https://www.cnblogs.com/Zingu/p/14640482.html
评论