2

Can someone please explain what is the difference between using await and the Result in the async pattern, and where would I use each?

public static async Task<string> GetVersion(int port, string method)
{
  var client = new HttpClient();
  client.BaseAddress = new Uri("http://localhost:" + port);
  return client.GetStringAsync("/test").Result;           //<===============this versus
  return await client.GetStringAsync("/test").ConfigureAwait(false);//<=====this
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
max
  • 9,708
  • 15
  • 89
  • 144
  • 1
    The `await` keyword triggers the `async` functionality. Without the `await`, It's just an ordinary synchronous method. To find out exactly how it works, read [Asynchronous Programming with Async and Await](http://msdn.microsoft.com/en-us/library/hh191443.aspx). – Robert Harvey Jan 16 '15 at 20:42
  • @Robert the marking of a method `async` has more overhead then it being run synchronously. – Yuval Itzchakov Jan 16 '15 at 20:45
  • @YuvalItzchakov: No doubt. – Robert Harvey Jan 16 '15 at 20:52

1 Answers1

5

Calling the Result will block the current thread until the operation completes. The await returns to the caller and continues with the rest of the method when the async operation is completed.

Sievajet
  • 3,443
  • 2
  • 18
  • 22
  • 2
    `will block the current thread until the operation completes` - or, very often, will block the current thread [for good](https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html). – GSerg Dec 08 '20 at 13:23