zoukankan      html  css  js  c++  java
  • List<T>.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)。

  • 相关阅读:
    shmget() 建立共享内存
    [转]SQL2005 连接问题处理
    [转]工作以后十不要,自勉
    C#学习笔记
    一位软件工程师6年总结(转)
    时间相关处理
    Litter Tips
    [转] VS打开解决方案时报错的处理方法
    面向对象—设计模式
    SQL Server 2000中的错误
  • 原文地址:https://www.cnblogs.com/catzhou/p/10275643.html
Copyright © 2011-2022 走看看