![](/img/trans.png)
[英]How can I wait till ten tasks are completed then execute the next ten tasks
[英]How to wait for all tasks to be completed
我有一個由兩部分組成的函數。 在執行第二部分之前需要第一部分的所有成功。
如:
ConcurrentDictionary<string, string> _dic = new ConcurrentDictionary<string, string>();
var _taskList = new List<Task>();
foreach (var item in someDataList)
{
_taskList.Add(new Task(async () =>
{
var result = await _req.ExecuteAsync(someParams).ConfigureAwait(false);
_dic.TryAdd(result.data, result.data);
}
}
_taskList.ForEach(t => t.Start());
await Task.WhenAll(_taskList.ToArray()).ConfigureAwait(false);
if (_dic.Count == List.count()
{
//execute part 2.
}
不是等待所有任務完成,字典中隨時沒有數據。 我嘗試:
while (true)
{
foreach (var item in _taskList)
{
if (item.Status == TaskStatus.Running)
goto continueWait;
}
}
但它也不起作用。
這是為什么? 我該怎么辦?
您的dict
不會有任何數據,因為傳入async
lambda 不會對Task
的構造函數產生任何影響。
您將需要大量重構代碼。 你想調用你的async
方法,把Task
放在你的列表中,然后await
它們完成。 完成后,您可以遍歷任務列表中的所有結果並從中提取.Result
。
var tasks = someDataList.Select(i => _req.ExecuteAsync(i) );
await Task.WhenAll(tasks);
var dict = tasks.ToDictionary(t=> t.Result);
if (dict.Count == List.count()
{
//execute part 2.
}
請注意,如果_dict
是一個全局變量並且您需要鎖定,那么您應該將ToDictionary
替換為上面的ConcurrentDictionary
代碼,因為這是示例代碼。
下面的異步循環示例代碼
var series = Enumerable.Range(1, 5).ToList();
var tasks = new List<Task<Tuple<int, bool>>>();
foreach (var i in series)
{
Console.WriteLine("Starting Process {0}", i);
tasks.Add(DoWorkAsync(i));
}
foreach (var task in await Task.WhenAll(tasks))
{
if (task.Item2)
{
Console.WriteLine("Ending Process {0}", task.Item1);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.