C#:使Task同时运行 [英] C#: Make Task run simultaneously

查看:463
本文介绍了C#:使Task同时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试不间断地连续运行多个任务. 这是我的代码:

I am trying to run Several Tasks continously, non-stop. Here is my code:

int maxThread = 100;
Task[] tasks = new Task[maxThreads];
while(true)
{
   for(int i = 0;i<maxThreads;i++)
   {
     tasks[i] = new Task.Factory.StartNew(someTask);
   }
   Task.WaitAll(tasks);
}

因此,此功能等待所有任务完成并运行下一批任务.但是我想在一项任务完成后立即开始一项任务,而不必等待其他任务.

So this function waits for all tasks to be completed and runs next batch of tasks. But I would like to start a task as soon as one is finished, without waiting for the other tasks.

谢谢!

推荐答案

我会使用SemaphoreSlim

int maxThread = 100;
SemaphoreSlim sem = new SemaphoreSlim(maxThread);

while (true)
{
    sem.Wait();
    Task.Factory.StartNew(someTask)
                .ContinueWith(t => sem.Release());
}

Parallel.ForEachvar po = new ParallelOptions(){MaxDegreeOfParallelism = 100};结合使用可以是另一种选择.但是Parallel.ForEach不保证它将使用100个任务.

Using Parallel.ForEach with var po = new ParallelOptions(){MaxDegreeOfParallelism = 100}; can be other alternative. But Parallel.ForEach doesn't guarantee it will use 100 Tasks for it.

这篇关于C#:使Task同时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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