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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM