call async method without await #2

后端 未结 3 711
花落未央
花落未央 2020-12-02 15:55

I have an async method:

public async Task ValidateRequestAsync(string userName, string password)
{
    using (HttpClient client = new HttpClient(         


        
3条回答
  •  死守一世寂寞
    2020-12-02 15:56

    If you call an async method from a single threaded execution context, such as a UI thread, and wait for the result synchronously, there is a high probability for deadlock. In your example, that probability is 100%

    Think about it. What happens when you call

    ValidateRequestAsync(userName, password).Result
    

    You call the method ValidateRequestAsync. In there you call ReadAsStringAsync. The result is that a task will be returned to the UI thread, with a continuation scheduled to continue executing on the UI thread when it becomes available. But of course, it will never become available, because it is waiting (blocked) for the task to finish. But the task can't finish, because it is waiting for the UI thread to become available. Deadlock.

    There are ways to prevent this deadlock, but they are all a Bad Idea. Just for completeness sake, the following might work:

    Task.Run(async () => await ValidateRequestAsync(userName, password)).Result;
    

    This is a bad idea, because you still block your UI thread waiting and doing nothing useful.

    So what is the solution then? Go async all the way. The original caller on the UI thread is probably some event handler, so make sure that is async.

提交回复
热议问题