SyncContext and ASP.NET Point Web API Extensions

When we deal with some extension points in the ASP.NET Web API, we also consider TAP (task-based programming pattern). In some cases, we want to ensure that the async method continues with ContinueWith , and we do some things inside the delegate that we pass to ContinueWith .

As Brad Wilson explained in detail here , SynchronizationContext is vital when we provide a sequel. For me, the only place I need to return to the SynchronizationContext in the ASP.NET Web API is the place where I need to play with HttpContext.Current (which I would never do in the ASP.NET Web API) and the place I need to set some information for the thread, for example Thread.CurrentPrincipal .

So the question is: do we want to return to the SynchronizationContext when we provide a continuation at some extensibility points, such as message handlers, filters, formatting, etc.?

+7
source share
1 answer

The answer is almost always yes.

Not to say that you will always use the synchronization context, but given the nature of message handlers, filters, and formatters, you cannot predict whether they will require the use of a SynchronizationContext in order to access the HttpContextBase .

Even with filters where you pass something that gives you access to the HttpContext (let's say through the IActionFilter implementation ) that the HttpContext will ultimately look at the current CallContext in the stream to provide information from this instance. Since the current thread (when starting async) does not have this information when starting Task , these calls will not be made.

However, if you need general, unlimited access to the HttpContextBase associated with the request, then you absolutely need to go around the SynchronizationContext in order to access it.

However, if possible, you should copy the data from the HttpContextBase that you need and transfer it; if you write something very generalized, then it will be impossible.

+2
source

All Articles