我将实现一个任务池,其中最多应该有console.log(characters);
个在paralell中运行的任务。
新作业可以从任何线程进入,并使用下一个免费任务。如果没有可用的任务,则应等待一个任务释放。完成所有工作后,任务应“休眠”以不占用CPU时间。
在C#/ .NET中是否已经有类似的东西?
谢谢!
答案 0 :(得分:0)
我将看一下TPL Dataflow Library中的Action块,这些块将为您提供所需的功能。在您指定的甚至更复杂的需求的生产环境中,我一直使用它。
答案 1 :(得分:0)
您可以轻松使用ConcurrentExclusiveSchedulerPair
。这是示例代码:
// max 3 parallel tasks
var schedulerPair = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 3);
var factory = new TaskFactory(schedulerPair.ConcurrentScheduler);
应使用following code开始新的Task
:
factory.StartNew(() => create task here).Unwrap()
完整示例:
static async Task Main(string[] args)
{
var schedulerPair = new ConcurrentExclusiveSchedulerPair(TaskScheduler.Default, 3);
var factory = new TaskFactory(schedulerPair.ConcurrentScheduler);
var tasks = new List<Task>();
Random r = new Random();
for (int i = 0; i < 5; i++)
{
var localI = i;
var ts = TimeSpan.FromMilliseconds(1000 + r.Next(0, 10) * 100);
var task = factory.StartNew(() => RunTask(localI, ts)).Unwrap();
tasks.Add(task);
}
await Task.WhenAll(tasks);
}
static object mutex = new object();
static int numberOfParallelWorkers;
static async Task RunTask(int n, TimeSpan delay)
{
for (int i = 0; i < 2; i++)
{
int nw;
lock (mutex) { nw = numberOfParallelWorkers = numberOfParallelWorkers + 1; }
var start = DateTime.Now;
Console.WriteLine($"Started task #{n} part {i} at {start:ss.ff}, tasks: {nw}");
Thread.Sleep(delay); // simulate CPU-bound work
lock (mutex) { nw = numberOfParallelWorkers = numberOfParallelWorkers - 1; }
var end = DateTime.Now;
Console.WriteLine($"Finished task #{n} part {i} at {end:ss.ff}, parallel: {nw}");
}
await Task.Yield();
}
产生以下输出:
Started task #1 part 0 at 43.98, parallel: 2
Started task #0 part 0 at 43.98, parallel: 1
Started task #2 part 0 at 43.98, parallel: 3
Finished task #0 part 0 at 45.09, parallel: 2
Started task #0 part 1 at 45.09, parallel: 3
Finished task #1 part 0 at 45.29, parallel: 2
Started task #1 part 1 at 45.29, parallel: 3
Finished task #2 part 0 at 45.59, parallel: 2
Started task #2 part 1 at 45.59, parallel: 3
Finished task #0 part 1 at 46.19, parallel: 2
Started task #3 part 0 at 46.19, parallel: 3
Finished task #1 part 1 at 46.59, parallel: 2
Started task #4 part 0 at 46.59, parallel: 3
Finished task #2 part 1 at 47.19, parallel: 2
Finished task #4 part 0 at 47.59, parallel: 1
Started task #4 part 1 at 47.59, parallel: 2
Finished task #3 part 0 at 47.69, parallel: 1
Started task #3 part 1 at 47.69, parallel: 2
Finished task #4 part 1 at 48.59, parallel: 1
Finished task #3 part 1 at 49.19, parallel: 0