68

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 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#.

Community
  • 1
  • 1
SB2055
  • 12,272
  • 32
  • 97
  • 202
  • @MickyD reading that, I see "// This method causes a deadlock when called in a GUI or ASP.NET context." - aren't WebApi and MVC leveraging .NET context? What would you do in the above scenario and why? – SB2055 Oct 23 '16 at 02:13
  • 1
    @MickyD I've read that several times and am still not clear. I must be stupid. "makes in ASP.NET is whether that thread enters the request context when resuming the method." - *Do I need to do this in the above scenarios?* - I can't possibly be the only one that would benefit from a straightforward example-based response here... Please don't mark as closed as this question is more geared towards API and MVC as opposed to generic C#. – SB2055 Oct 23 '16 at 03:37
  • 2
    http://stackoverflow.com/questions/18970400/async-await-unexpected-behaviour-of-configureawait would be more entertaining read... On other hand if you/your team is very disciplined and does not ever use global values (like current Http context or current culture) you are fine either way. Also http://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-code is the answer your are looking for - not really clear how your question is different (or why you expect any other answer than - no point to call `ConfigureAwait(false)` in server side code) – Alexei Levenkov Oct 23 '16 at 03:46
  • 5
    "no point to call ConfigureAwait(false)" < This statement right here is why I remain confused. Conflicting guidance without any *straightforward, example-based* answer. – SB2055 Oct 23 '16 at 04:11
  • Isn't there a question of scale here, freeing up the UI thread on long-running API calls to service more requests? The action with ConfigureAwait(false) will resume on the next available thread rather than holding on to the one that made the request, to begin with. Whereas there is not a performance increase for each request, there is a scale increase, allowing more requests to complete instead of a long-running task hogging the thread from a limited thread pool. – Observer Mar 08 '21 at 08:44

4 Answers4

89

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 2
    Any update on this Stephen? I'm writing controller code in asp.net core mvc and wondering what the implications are of using/not using `ConfigureAwait(false)`. Your side note doesn't really help - if ASP.NET Core has no context, does that mean I should use `ConfigureAwait(false)`? – David Clarke Feb 28 '18 at 21:12
  • 3
    @DavidClarke: Since there's no context, `ConfigureAwait(false)` has no effect. More info: https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html – Stephen Cleary Feb 28 '18 at 23:39
  • @StephenCleary thanks, that was an exceptionally helpful reference – David Clarke Mar 01 '18 at 20:54
  • Is there a way to find which ASP.NET methods rely on the context? – Landerah Dec 03 '18 at 07:22
  • @Landerah: Not to my knowledge. Even if you could, it would be an implementation detail that can change with the next version. And it doesn't really matter much at this point anyway, since ASP.NET Core is the future. – Stephen Cleary Dec 03 '18 at 19:17
  • @StephenCleary is there a context, `HttpContext.Current.Response`, in .NET Framework 4.7.2 WebAPI2 that we need to worry about when using `ConfigureAwait(false)`? – rboy Mar 24 '21 at 22:25
  • @rboy: Yes. `HttpContext.Current` is part of the context. – Stephen Cleary Mar 25 '21 at 01:36
  • @StephenCleary this usually means that we are OK to NOT await this async method, and it is fine that this async method is fire and forget? – kuldeep Jan 27 '22 at 15:45
  • @kuldeep: There's nothing in this question or answer that has anything to do with fire-and-forget. – Stephen Cleary Jan 27 '22 at 16:37
  • @StephenCleary sorry for confusion, but i have noticed sometimes use of ConfigureAwait without await keyword and sometimes with await keyword. So if we are using it in a method that has no Task or Task being returned, is this ok to use ConfigureAwait(false) without await keyword? – kuldeep Jan 28 '22 at 03:51
  • 1
    @kuldeep: `ConfigureAwait` configures the `await`. If there's no `await`, then it doesn't do anything. – Stephen Cleary Jan 28 '22 at 14:04
  • Thanks for your reply, so if there is no await then it is treated as synchronous (blocking) call ? – kuldeep Jan 29 '22 at 07:44
  • 2
    @kuldeep: No; it would be fire-and-forget, which is almost never what you want. Feel free to ask your own question if you want more information. – Stephen Cleary Jan 29 '22 at 09:45
1

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.

ferarias
  • 333
  • 2
  • 11
  • "it should do no harm nor good" - there's actually a performance improvement because it doesn't have to switch synchronisation context for the continuation. – David Klempfner Sep 02 '22 at 04:46
-4

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

Dev-Systematix
  • 439
  • 6
  • 26
-7

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.

  • 3
    ConfigureAwait(false) does not disable asynchronous await! It simply means use whatever context is available to resume execution when the said async method completes – Shishir Gupta May 05 '19 at 08:46