0

I am trying to understand why the following Task.Run and GetAwaiter().GetResult() would be used instead of await ... <result>

(var success, var response) = Task.Run(() => HTTPHelper.SendRequest<SomeJsonResponse>( ... )).GetAwaiter().GetResult();

Does the code above throw, as this article shows, an Exception and not an AggregateException? If so, I believe that is why this structure was chosen.

Is it possible to use async ... await in this situation and have the same result? (I assume not, if the single exception requirement is only possible with the code above.)

Matt W
  • 11,753
  • 25
  • 118
  • 215
  • 1
    *"instead of `await ... .Result`"* - You never use `.Result` with `await`. It just wouldn't work. The `await` keyword unwraps the result for you. – Gabriel Luci Oct 29 '19 at 13:22
  • 1
    Microsoft's articles on asynchronous programming are actually quite well written. You might benefit from reading through them. Start here: [Asynchronous programming with async and await](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/) – Gabriel Luci Oct 29 '19 at 13:27

1 Answers1

1

Yeah, you can and should use async await :

(var success, var response) = await HTTPHelper.SendRequest<SomeJsonResponse>( ... )

Then there is no need to wrap it into the Task. I assume .SendRequest<SomeJsonResponse>() returns the Task.

FYI: .Wait(), .Result or GetAwaiter().GetResult() are all thread blocking executions

OlegI
  • 5,472
  • 4
  • 23
  • 31
  • I found this interesting: https://stackoverflow.com/a/38530225/71376 – Matt W Oct 29 '19 at 10:48
  • Actually, in answer to your question, I believe the `.SendRequest` does not return a task, partly because it is a legacy method, hence `Task.Run()` – Matt W Oct 29 '19 at 10:49
  • 1
    @MattW yes it’s basically workaround if you aren’t able to change method signature to return Task – OlegI Oct 29 '19 at 10:49
  • Thanks :) Looks like there's lots of differing opinions (or at least, history) on this topic. Even the post marked as the original of this duplicate appears to be claiming the answer in two different directions (well, the responses do, anyway.) – Matt W Oct 29 '19 at 10:51
  • 1
    @MattW Everyone agrees that you should use `await` if you can. The disagreements are only about how to go about synchronously waiting on an asynchronous method (which you should make an effort to avoid doing in the first place). – Gabriel Luci Oct 29 '19 at 13:24