Reputation: 3289
I came across these statements in a project that I am maintaining:
var response = Task.Run(() =>
{
return httpClient.PostAsync(myUrl, myPayload);
}).Result;
It runs, on a different thread, an asynchronous method to make an HTTP request.
Unless I am missing something, is there any additional benefit in running an asynchronous method on a different thread? Wouldn't this be good enough?
var response = await httpClient.PostAsync(myUrl, myPayload);
Upvotes: 0
Views: 75
Reputation: 456322
Unless I am missing something, is there any additional benefit in running an asynchronous method on a different thread?
The existing code doesn't just use Task.Run
; it uses Task.Run
and then blocks on the resulting task. This is a variant of the "thread pool hack" which is one way to block on asynchronous code. Although the code should be using GetAwaiter().GetResult()
rather than Result
.
Many libraries support blocking directly rather than requiring the thread pool hack. HttpClient
in particular mostly does, but there are some platforms (mobile platforms, IIRC) where HttpClient
had a bug where you couldn't block directly on it. So it's most likely that this code is intended as a "blocking hack".
There is another reason for running an asynchronous method on a thread pool thread: if that thread does some synchronous work. Again, this is a known issue with HttpClient
; the proxy resolution and DNS lookup is done synchronously. If the existing code was await Task.Run(() => ...);
instead of Task.Run(() => ...).Result;
, then I would think this alternative explanation would be more likely.
Upvotes: 2
Reputation: 849
Assuming you understand your first example use .Result
which is blocking and second using await
do not.
Now to answer your question -
It runs, on a different thread, an asynchronous method to make an HTTP request.
Unless I am missing something, is there any additional benefit in running an asynchronous method on a different thread? Wouldn't this be good enough?
There is no benefit in blocking an additional thread just to wait for the POST
call to return data.
And yes this is recommended way of doing it -
var response = await httpClient.PostAsync(myUrl, myPayload);
You can read more details here
Upvotes: 2