Is there any danger in using ConfigureAwait(false) in WebApi or MVC controllers?

C#.Netasp.net MvcAsynchronousasp.net Web-Api

C# Problem Overview


Say I have two scenarios:

1) WebApi Controller

    [System.Web.Http.HttpPost]
    [System.Web.Http.AllowAnonymous]
    [Route("api/registerMobile")]
    public async Task<HttpResponseMessage> RegisterMobile(RegisterModel model)
    {
        var registerResponse = await AuthUtilities.RegisterUserAsync(model, _userService, User);
        if (registerResponse.Success) {
            var response = await _userService.GetAuthViewModelAsync(model.Username, User);
            return Request.CreateResponse(HttpStatusCode.OK, new ApiResponseDto() { Success = true, Data = response });
        }
        else {
            return Request.CreateResponse(HttpStatusCode.OK, registerResponse);
        }

    }

2) MVC Controller

    [Route("public")]
    public async Task<ActionResult> Public()
    {
        if (User.Identity.IsAuthenticated)
        {
            var model = await _userService.GetAuthViewModelAsync(User.Identity.Name);
            return View("~/Views/Home/Index.cshtml", model);
        }
        else
        {
            var model = await _userService.GetAuthViewModelAsync(null);
            return View("~/Views/Home/Index.cshtml", model);
        }
    }

I've been reading up on when I should use ConfigureAwait and it seems like I should use ConfigureAwait(false) on ALL of my async calls that are not tied directly to the UI. I don't know what that means though... should I be using .ConfigureAwait(false) on all of the above await calls?

I'm looking for some unambiguous guidelines around when exactly I should be using it.

This question is NOT the same as the https://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-code - I am looking for a straightforward answer on the use-case for this method in the context of WebApi and MVC, not as general C#.

C# Solutions


Solution 1 - C#

> it seems like I should use ConfigureAwait(false) on ALL of my async calls that are not tied directly to the UI.

Not quite. That guideline doesn't make sense here, since there is no UI thread.

The parameter passed to ConfigureAwait is continueOnCapturedContext, which explains more clearly the scenario. You want to use ConfigureAwait(false) whenever the rest of that async method does not depend on the current context.

In ASP.NET 4.x, the "context" is the request context, which includes things like HttpContext.Current and culture. Also - and this is the undocumented part - a lot of the ASP.NET helper methods do depend on the request context.

(Side note: ASP.NET Core no longer has a "context")

> should I be using .ConfigureAwait(false) on all of the above await calls?

I haven't heard any firm guidance on this, but I suspect it's OK.

In my own code, I never use ConfigureAwait(false) in my controller action methods, so that they complete already within the request context. It just seems more right to me.

Solution 2 - C#

If there's no actual context in a ASP.NET Core application, it should do no harm nor good to add .ConfigureAwait(false) to your awaitable methods into controllers.

However, if there is a chance that eventually in the future, for whatever reason, there's something like a context to be taken into account as in ASP.NET 4, that would be a different story. We could not risk running in a different context, unless we don't give a damn about it (in which case we could use whatever thread is available for processing, thus possibly improving performance).

My choice here is to add ConfigureAwait(false) even if it's not used.

Solution 3 - C#

You may use ConfigureAwait on public action MVC Controller, it help to prevent deal lock if your _userService.GetAuthViewModelAsync keeps waiting. it cloud raise deadlock if async service keeps await so by may block httpcontext of UI.

Have look below link to understand this case:

http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

Solution 4 - C#

Using ConfigureAwait(false) in controllers does not sound good to me as it will make main thread wait until the operation is finished. The best I figured out is to use it in your Service/Business layer and Persistance layer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSB2055View Question on Stackoverflow
Solution 1 - C#Stephen ClearyView Answer on Stackoverflow
Solution 2 - C#ferariasView Answer on Stackoverflow
Solution 3 - C#Dev-SystematixView Answer on Stackoverflow
Solution 4 - C#Smit JawaleView Answer on Stackoverflow