有這麼個非同步方法 private static async Task Compute(int s) { return await Task.Run(() = { if (s s = new List { 1, 2, 3, 4, 5 }; List t = new List(); s.ForEach( ...
有這麼個非同步方法
private static async Task<int> Compute(int s)
{
return await Task<int>.Run(() =>
{
if (s < 5)
return s * 2;
else
return s * 3;
});
}
當然實際過程是從資料庫獲取或者從網路上獲取什麼內容。
現在我想調用:
private static void Main(string[] args)
{
List<int> s = new List<int> { 1, 2, 3, 4, 5 };
List<int> t = new List<int>();
s.ForEach(ii =>
{
int ret = await Compute(ii);
t.Add(ret);
});
t.ForEach(ii => Console.WriteLine(ii));
}
發現 vs 划了一條下劃線
OK,await 必須 async的,簡單,改一下
private static void Main(string[] args)
{
List<int> s = new List<int> { 1, 2, 3, 4, 5 };
List<int> t = new List<int>();
s.ForEach(async ii =>
{
int ret = await Compute(ii);
t.Add(ret);
});
t.ForEach(ii => Console.WriteLine(ii));
}
然後,Ctrl+F5運行,報錯了!
錯誤在
t.ForEach(ii => Console.WriteLine(ii));
原因在:Foreach 調用了一個 async void 的Action,沒有await(也沒法await,並且await 沒返回值的也要設成Task,沒法設)
老老實實改成 foreach(var ii in s)。