If you have worked with Asp.Net MVC, you are probably familiar with this word. When a request is sent to Asp.Net MVC applications, request information such as Uri, Headers, RemoteAddress, etc. is contained in HttpContext.Current. HttpContext.Current information is on the current thread, and when you call an async method as ConfigureAwait(false), it is very likely that another thread will continue to work, and this is often the case, and the HttpContext.Current will be null because the thread has been changed. To do this, you must use ConfigureAwait(true) or don't call  ConfigureAwait() method where you need HttpContext.Current information. For example, in the following action, we first receive the request information and then call an async method as ConfigureAwait (false) and then retrieve the request information from HttpContext.

public class ValuesController : ApiController
{
    public async Task<IHttpActionResult> Get()
    {
        var beforeConfigureAwaitFalse = HttpContext.Current.Request.Url.AbsoluteUri;

        await DoSomething().ConfigureAwait(false);

        var afterConfigureAwaitFalse = HttpContext.Current?.Request?.Url?.AbsoluteUri ?? "null";

        return Json(new
        {
            beforeConfigureAwaitFalse,
            afterConfigureAwaitFalse
        });
    }

    private async Task DoSomething()
    {
        await Task.Delay(1000);
    }
}

If you run the program, and call the action, most of the afterConfigureAwaitFalse variable will be null because when we use ConfigureAwait(false) the current HttpContext information will not be captured and the next thread that continues will have no HttpContext information. You will receive the following output:

{
  "beforeConfigureAwaitFalse": "https://localhost:44338/api/values",
  "afterConfigureAwaitFalse": "null"
}

But if you change the value of ConfigureAwait(false) to ConfigureAwait(true), the current HttpContext information is captured and assigned by SynchronizationContext to the new thread that continues.
Now if you run the following code:

public async Task<IHttpActionResult> Get()
{
    var beforeConfigureAwaitFalse = HttpContext.Current.Request.Url.AbsoluteUri;

    await DoSomething().ConfigureAwait(true);

    var afterConfigureAwaitFalse = HttpContext.Current?.Request?.Url?.AbsoluteUri ?? "null";

    return Json(new
    {
        beforeConfigureAwaitFalse,
        afterConfigureAwaitFalse
    });
}

You will always receive the following output:

{
  "beforeConfigureAwaitFalse": "https://localhost:44338/api/values",
  "afterConfigureAwaitFalse": "https://localhost:44338/api/values"
}

Note: By default, if you do not call the ConfigureAwait method, the current HttpContext will be captured.

;)

Powered by Froala Editor

Comments