码迷,mamicode.com
首页 > 其他好文 > 详细

List<T>.ForEach 调用异步方法的意外

时间:2019-01-16 11:41:28      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:OLE   main   原因   inf   lse   分享   code   info   数据库   

有这么个异步方法

 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)。

List<T>.ForEach 调用异步方法的意外

标签:OLE   main   原因   inf   lse   分享   code   info   数据库   

原文地址:https://www.cnblogs.com/catzhou/p/10275643.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!