Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net vs MVC vs WebAPI and UseTaskFriendlySynchronizationContext

I've got a couple ASP.Net MVC and WebAPI projects. Most of them are up to date (MVC 5 / WebAPI 2). I've been double-checking my security assumptions since I'm implementing a global filter (for MVC) and a delegating handler (for WebAPI) to unify security across the system.

In that context, I've come across a few articles and posts (see below) which say you should always be setting UseTaskFriendlySynchronizationContext to true (it defaults to false). This seems odd to me as even in VS2013 using MVC 5 and WebAPI 2 new project templates (as well as the ASP.Net WebForms template) do not set this app setting at all.

The MSDN documentation on this setting is practically non-existent and the posts I've found that do say it's required for async programming seem to be in the context of WebForms.

So here are my questions:

  1. Does this setting apply to everything ASP.Net or is it specific to the page lifecycle stuff in ASP.Net (which I've not used much)
  2. If it is so critical for modern async programming, why don't any tutorials or templates reference it?
  3. Would using Thread.CurrentPrincipal's claims in a referenced library that uses ConfigureAwait(false) pose any problems or will the flowing of ExecutionContext's logical call context take care of me there? (my reading and testing so far indicates that it will)

Here are some of the articles I've seen regarding UseTaskFriendlySynchronizationContext:

  • Set Thread.CurrentPrincipal Asynchronously?
  • ASP.NET appSettings Element on MSDN
  • What's the meaning of "UseTaskFriendlySynchronizationContext"?
  • Understanding the SynchronizationContext in ASP.NET by Marcus van Houdt
  • Why is an "await Task.Yield()" required for Thread.CurrentPrincipal to flow correctly?

Some articles that really helped me get a grasp on how all this stuff works that never mention UseTaskFriendlySynchronizationContext:

  • ExecutionContext vs SynchronizationContext by Stephen Toub
  • It's All About the SynchronizationContext by Stephen Cleary
like image 479
Madeline Trotter Avatar asked Dec 09 '13 18:12

Madeline Trotter


1 Answers

The missing key reference is this blog post. Specifically, you need to either set UseTaskFriendlySynchronizationContext or set targetFramework to 4.5. Creating a new project sets targetFramework to 4.5, so you do get the correct behavior (UseTaskFriendlySynchronizationContext is implicitly set to true).

To answer your specific questions:

  1. The setting affects ASP.NET request handling for all kinds of requests, not just WebForms.
  2. Most async tutorials assume a GUI application scenario.
  3. I'm not sure; I think this would be better as a separate question. My gut feeling is that you can't depend on Thread.CurrentPrincipal after you leave the ASP.NET context.
like image 190
Stephen Cleary Avatar answered Sep 21 '22 05:09

Stephen Cleary