有这么个异步方法数据库
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 划了一条下划线async
OK,await 必须 async的,简单,改一下3d
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运行,报错了!
code
错误在blog
t.ForEach(ii => Console.WriteLine(ii));
缘由在:Foreach 调用了一个 async void 的Action,没有await(也无法await,而且await 没返回值的也要设成Task,无法设)
老老实实改为 foreach(var ii in s)。string