我正在使用Task.Factory.StartNew异步调用Sync方法。 Async完成后,我需要它的结果。我正在并行运行此任务,并将每个结果组合在一个结果中,如下所示 -
public List<Nomination> Submit(List<Nomination> nominations, string userEmail)
{
var sublist = new List<Nomination>();
int nSize = 5;
var submitedList = new List<Nomination>();
List<Task> tasks = new List<Task>();
for (int index = 0; index < nominations.Count; index += nSize) // No nominations in a batch
{
sublist = nominations.GetRange(index, Math.Min(nSize, nominations.Count - index));
//SubmitNomination is sync method which does some db operation and returns a List<Nomination>
Task<List<DTO.FeedbackRequest>> task = Task.Factory.StartNew( () => { return SubmitNomination(sublist, userEmailName); });
Task cont = task.ContinueWith(submitted => {
submitedList.AddRange(submitted.Result);
});
tasks.Add(cont);
}
Task.WaitAll(tasks.ToArray());
return submitedList;
}
当我看到submitedList时,我得到的列表计数一直在变化。它假设是作为输入的提名计数。
请告诉我如何解决这个问题。
非常感谢,Thirumalai M
答案 0 :(得分:1)
两个选项
将submitedList
更改为并发类型,例如ConcurrentBag<T>
。在预期您的后续问题时,请why you can't just use a concurrent list:)