C#无法从';无效';至';System.Threading.Tasks.Task
搜索后,我没有找到与我的问题相关的主题,因此,这里是: 由于我们调用的服务有限,我们计划每次并行触发预定义数量的服务请求。代码是:C#无法从';无效';至';System.Threading.Tasks.Task,c#,concurrency,C#,Concurrency,搜索后,我没有找到与我的问题相关的主题,因此,这里是: 由于我们调用的服务有限,我们计划每次并行触发预定义数量的服务请求。代码是: public static void RunConcurrentThreads(List<Item> list, Action<Item> action, int nNumberOfConcurrentThreads = 3) { for (int i = 0; i < list.Count; i
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;
}
}
publicstaticvoid运行ConcurrentThreads(列表、动作、int nNumberOfConcurrentThreads=3)
{
for(int i=0;i0)
{
Task.WaitAll(taskList.ToArray());
}
i=i+n当前线程数;
}
}
“Item”是一个定义我们正在处理的对象的类
“action”用于以一个Item对象作为参数的void方法。该方法将调用一个服务,然后将返回的信息保存到数据库中。大约需要0.5-1秒才能完成
nNumberOfConcurrentThreads是每次将激发的并发请求数
这一行给出了标题中的错误
添加(操作(列表[i+j])
那么,如何修复错误呢?还是有更好的方法来处理这种并发问题
谢谢。
操作
不会返回任何内容。如果要在任务中运行它
需要调用Task.run
,它在单独的线程中开始运行操作并返回任务:
taskList.Add(Task.Run(() => action(list[i + j]));
Microsoft已使用为您完成了这项工作 使用起来很简单
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)
);
}
使用System.Threading.Tasks;
静态void RunConcurrentThreads(列表、操作、int nNumberOfConcurrentThreads=3)
{
并行循环
(
列表
新的并行选项{MaxDegreeOfParallelism=nNumberOfConcurrentThreads}
i=>行动(i)
);
}
虽然这看起来像一个循环,但实际上运行时将为每个迭代创建一个线程(达到指定的限制),并并行运行它们