[英]Parallel using tasks
I am currently creating an engine that will spin 10 new threads up that will do diffrent work. 我当前正在创建一个引擎,该引擎将启动10个新线程来完成不同的工作。 But i have found that my solution dose not run in Parallel. 但是我发现我的解决方案不能并行运行。
public async Task Start(Func<string, Task> action)
{
for (var i = 1; i <= config.threads; i++)
{
consumers.Add(getActionTask(action));
}
await Task.WhenAll(consumers);
}
private Task getActionTask(Func<string, Task> action)
{
return Task.Run(async () =>
{
// Do something that returns a string
String data = "Some string here";
await action(data);
}
}
Lets say i run 2 threads, and based on data will the first thread do a Task.Delay(TimeSpan.FromSeconds(30));
假设我运行2个线程,并且第一个线程将基于数据执行Task.Delay(TimeSpan.FromSeconds(30));
The second thread will print "Hello" on a loop. 第二个线程将在循环上打印“ Hello”。
It will never get the print loop before the Delay is over, what is wrong with my implementation? 在Delay结束之前它将永远不会获得打印循环,我的实现有什么问题?
The Task.WhenAll
doesn't say that the tasks will run in parallel. Task.WhenAll
并不表示任务将并行运行。 It creates a Task
that would be completed once all the tasks you pass as an argument to the WhenAll
method would be completed. 它创建了一个Task
,一旦您将作为参数传递给WhenAll
方法的所有任务都将完成,该任务将完成。
If you want your code to run in parallel, you should make use of the Parallel
class ForEach
method. 如果希望代码并行运行,则应使用Parallel
类ForEach
方法。
Update 更新
One important note as Scott pointed out below in his comment is that the functions in the Parallel
class do not work with async methods. 正如Scott在下面的评论中指出的一个重要说明,即Parallel
类中的函数不适用于异步方法。 If you want to use async methods with it you must use TPL Dataflow instead. 如果要使用异步方法,则必须改用TPL Dataflow 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.