Page 121 - CSharp/C#
P. 121
// Block waiting for the result synchronously
ActionResult result = Task.Result;
return result;
}
This can avoid deadlocks when it is necessary to block on asynchronous code, however this
comes at the cost of losing the context in the continuation (code after the call to await).
In ASP.NET this means that if your code following a call to await someTask.ConfigureAwait(false);
attempts to access information from the context, for example HttpContext.Current.User then the
information has been lost. In this case the HttpContext.Current is null. For example:
public async Task<ActionResult> Index()
{
// Contains information about the user sending the request
var user = System.Web.HttpContext.Current.User;
using (var client = new HttpClient())
{
await client.GetAsync("http://google.com").ConfigureAwait(false);
}
// Null Reference Exception, Current is null
var user2 = System.Web.HttpContext.Current.User;
return View();
}
If ConfigureAwait(true) is used (equivalent to having no ConfigureAwait at all) then both user and
user2 are populated with the same data.
For this reason it is often recommended to use ConfigureAwait(false) in library code where the
context is no longer used.
Async/await
See below for a simple example of how to use async/await to do some time intensive stuff in a
background process while maintaining the option of doing some other stuff that do not need to wait
on the time intensive stuff to complete.
However, if you need to work with the result of the time intensive method later, you can do this by
awaiting the execution.
public async Task ProcessDataAsync()
{
// Start the time intensive method
Task<int> task = TimeintensiveMethod(@"PATH_TO_SOME_FILE");
// Control returns here before TimeintensiveMethod returns
Console.WriteLine("You can read this while TimeintensiveMethod is still running.");
// Wait for TimeintensiveMethod to complete and get its result
int x = await task;
https://riptutorial.com/ 67

