Why does this async code sometimes fail, and only when not observed?

后端 未结 3 1742
情书的邮戳
情书的邮戳 2021-01-19 15:59

This is the original code that had been running fine for a few weeks. In a test I just did, it failed 0 out of 100 attempts.

using (var httpClient = new Http         


        
3条回答
  •  醉话见心
    2021-01-19 16:20

    To address the comment from to your other question, you very rarely need to mix async/await with ContinueWith. You can do the "fork" logic with help of async lambdas, e.g., the code from the question may look like this:

    using (var httpClient = new HttpClient())
    {
        Func>> doTask1Async = async () =>
        {
            var request = await httpClient.GetAsync(new Uri("..."));
            return response.Content.ReadAsAsync>();
        };
    
        Func>> doTask2Async = async () =>
        {
            var request = await httpClient.GetAsync(new Uri("..."));
            return response.Content.ReadAsAsync>();
        };
    
        var task1 = doTask1Async();
        var task2 = doTask2Async();
    
        await Task.WhenAll(task1, task2);
    
        var result1 = task1.Result;
        var result2 = task2.Result;
    
        // ...
    }
    

提交回复
热议问题