This project is read-only.

SynchronizationContext and ASP.NET Web API Extensibility Points

Topics: ASP.NET Web API
Jul 25, 2012 at 12:11 PM

When we are dealing with some extensibility points in ASP.NET Web API, we also deal with TAP. At some points, we want to provide a continuation to an async method with ContinueWith and we do some stuff inside the delegate that we pass onto ContinueWith.

As Brad Wilson explained here in depth, the SynchronizationContext is vital when we provide continuations:

For me, the only place where I need to get back to the SynchronizationContext in an ASP.NET Web API is the place where I need to play with HttpContext.Current (which is something that I would never do in an ASP.NET Web API application). So the question is:

Do we ever want to get back to the SynchronizationContext when we provide continuations in some extensibility points such as Message Handlers, Filters, Formatters, etc.?

Feb 26, 2014 at 9:48 PM
Surprised that there's no answer to this
Feb 27, 2014 at 1:51 PM
I think in every case where you are writing the code for any of the extenssibility point, you should sync back to SyncContext as ASP.NET Web API needs the current HttpContext even if you explicitly don't. E.g.

Maybe the formatters may be an exception to this but not sure on that, too.

I would be also very happy if someone from the team would clear this out but I'm syncing back to SyncContex every case as a result.
Feb 27, 2014 at 3:28 PM
What about in OWIN hosted situations, particularly self host? HttpContext is null in those instances no?
Feb 27, 2014 at 4:25 PM
What do you mean by OWIN hosted? You can target OWIN but this doesn't mean you are not on top of ASP.NET. E.g:
Feb 27, 2014 at 5:25 PM
I think he refers to selfhost scenarios. Thus we don't have a dependency on the static HttpContext.
Feb 27, 2014 at 5:43 PM
I think he refers to selfhost scenarios. Thus we don't have a dependency on the static HttpContext.
If it's the case that yishaigalatzerer indicated above, that's a tricky question.

As far as I know, any of the OWIN hosting options from Project Katana does not have their own SynchronizationContext (of course, except for Microsoft.Owin.Host.SystemWeb). However, you won't know for sure if the ones that we are not aware have it.

So, if you are writing ASP.NET Web API components (message handlers, filters, etc.) that you will distribute through NuGet or any other ways, IMO, you should always sync back to SynchronizationContext as you don't know for sure (even if you target OWIN).