我有一個簡單的問題 - 爲什麼異步方法不會等待並行循環完成?並行和異步方法
public async Task<List<object>> DoSomeAsync()
{
// some async actions with streams and web requests
// ...
ConcurrentQueue<object> queue = new ConcurrentQueue<object>();
Parallel.For(1, x, async i =>
{
// a little chunk of code
// ...
queue.Enqueue(new object());
// ...
// a little chunk of code again
}
return queue.ToList(); // debugger says that this statement is executed earlier than parallel loop.
}
你知道我有什麼想法,我該如何等待執行並行循環?
可能您需要'await Parallel.For(...)' – Grundy
並行循環無法等待,因爲它們不返回任務實例。 – vdrake6
Parallel.For'循環裏面有沒有'awaitable'方法? – GeorgeChond