[英]C# Cannot convert from 'void' to 'System.Threading.Tasks.Task
After searching I didn't find a related topic to my problem so here it goes: 搜索之后,我没有找到与我的问题相关的主题,因此请按以下步骤进行:
Due to the limit of the service we are calling, we plan to fire a pre-defined number of service requests in parallel each time. 由于我们要调用的服务有限,我们计划每次并行触发一个预定数量的服务请求。 The code is:
代码是:
public static void RunConcurrentThreads(List<Item> list, Action<Item> action, int nNumberOfConcurrentThreads = 3)
{
for (int i = 0; i < list.Count; i++)
{
var taskList = new List<Task>();
for (int j = 0; j < nNumberOfConcurrentThreads; j++)
{
if (i + j < list.Count)
{
taskList.Add(action(list[i + j]));
}
else
{
break;
}
}
if (taskList.Count > 0)
{
Task.WaitAll(taskList.ToArray());
}
i = i + nNumberOfConcurrentThreads;
}
}
The "Item" is a class that defines the object we are dealing with. “ Item”是一个类,定义了我们要处理的对象。
"action" is for a void method that take one Item object as parameter. “操作”用于将一个Item对象作为参数的void方法。 The method will call a service, then save returned information to database.
该方法将调用服务,然后将返回的信息保存到数据库。 It takes about 0.5 - 1 second to finish.
完成大约需要0.5-1秒。
nNumberOfConcurrentThreads is the number of concurrent requests that will be fired at each time. nNumberOfConcurrentThreads是每次将触发的并发请求数。
This line is giving the error in the title 该行显示标题错误
taskList.Add(action(list[i + j]));
taskList.Add(action(list [i + j]));
So how to fix the error? 那么如何解决错误? Or is there a better way to handle this kind of concurrency problem?
还是有更好的方法来处理此类并发问题?
Thank you. 谢谢。
Microsoft has done the work for you with the Task Parallel Library . Microsoft已使用任务并行库为您完成了工作。
Just use Parallel.ForEach and it's simple. 只需使用Parallel.ForEach ,它就很简单。
using System.Threading.Tasks;
static void RunConcurrentThreads(List<Item> list, Action<Item> action, int nNumberOfConcurrentThreads = 3)
{
Parallel.ForEach
(
list,
new ParallelOptions { MaxDegreeOfParallelism = nNumberOfConcurrentThreads }
i => action(i)
);
}
While this looks like a loop, in reality the runtime will create a thread for each iteration (up to the limit specified) and run them in parallel. 虽然这看起来像一个循环,但实际上,运行时将为每次迭代创建一个线程(达到指定的限制)并并行运行它们。
Action
doesn't return anything. Action
不返回任何东西。 If you want to run it in a Task
you need to call Task.Run
which starts running the action in a separate thread and returns the task: 如果要在
Task
运行它,则需要调用Task.Run
,它开始在单独的线程中运行该操作并返回任务:
taskList.Add(Task.Run(() => action(list[i + j]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.