What happens while waiting on a Task's Result?

后端 未结 2 1512
长情又很酷
长情又很酷 2020-11-30 06:40

I\'m using the HttpClient to post data to a remote service in a .NET 4.0 project. I\'m not concerned with this operation blocking, so I figured I could skip ContinueWith or

2条回答
  •  情书的邮戳
    2020-11-30 07:06

    In Windows, all I/O is asynchronous. Synchronous APIs are just a convenient abstraction.

    So, when you use HttpWebRequest.GetResponse, what actually happens is the I/O is started (asynchronously), and the calling thread (synchronously) blocks, waiting for it to complete.

    Similarly, when you use HttpClient.PostAsync(..).Result, the I/O is started (asynchronously), and the calling thread (synchronously) blocks, waiting for it to complete.

    I usually recommend people use await rather than Task.Result or Task.Wait for the following reasons:

    1. If you block on a Task that is the result of an async method, you can easily get into a deadlock situation.
    2. Task.Result and Task.Wait wrap any exceptions in an AggregateException (because those APIs are holdovers from the TPL). So error handling is more complex.

    However, if you're aware of these limitations, there are some situations where blocking on a Task can be useful (e.g., in a Console application's Main).

提交回复
热议问题