Running a task through an ASP.NET synchronization context is safe and without AsyncManager.Sync

I am trying to mix AsyncController with dependency injection. The corresponding MVC application receives almost all of its data through asynchronous web service calls. We complete the asynchronous operation in Tasks from TPL and notify the AsyncManager controller of the completion of these tasks.

Sometimes we have to touch HttpContext to continue these tasks - adding a cookie, whatever. The correct way to do this in accordance with Using an Asynchronous Controller in ASP.NET MVC is to call a method AsyncManager.Sync. This will propagate the context of the ASP.NET stream, including the HttpContext, into the current stream, make a callback, and then restore the previous context.

However, this article also states:

Calling Sync () from a thread that is already running ASP.NET has undefined behavior.

This is not a problem if you are doing all your work in the controller, as you usually know which thread you should be included in the sequels. But what I'm trying to do is create a middle tier between our access to async data and our asynchronous controllers. Thus, they are also asynchronous. Everything is connected by a DI container.

As before, some components in the call chain will need to work with the “current” HttpContext. For example, after logging in, we want to save the session token, which we return from the single sign-on service. The abstraction for what this is doing is ISessionStore. Think of a CookieSessionStore that puts a cookie in response or grabs a cookie from a request.

, :

  • AsyncManager , .
  • , , AsyncManager.Sync .

# 1, , TaskScheduler.FromCurrentSynchronizationContext() , , HttpContextBase .

, , :

MySyncObject.Sync(httpContext => /* Add a cookie or something else */);

, №2. AsyncManager, SynchronizationContextTaskScheduler Reflector, , ASP.NET SynchronizationContext. :)

, , , , . , , , , Task.Start(scheduler). , , , .

, :

  • ?
  • ?
  • HttpContext? HttpContextBase (ick)?
+5
1

- , . HttpContext.Current , , , , . , , . , :

public async Task<ActionResult> MyAction() {
    var context = HttpContext.Current;
    await Task.Yield();
    var item = context.Items["something"];
    await Task.Yield();
    return new EmptyResult();
}

, HttpContext.Current , MVC:

public async Task<ActionResult> MyAction() {
    await Task.Yield();
    var item = this.HttpContext.Items["something"];
    await Task.Yield();
    return new EmptyResult();
}

, - , , HttpContext - ASP.NET. , , ( , ..) cookie, this.HttpContext .

+1

All Articles