morpheus
morpheus

Reputation: 20380

How does ASP.NET MVC3 avoid multithreading bugs by sharing single instance of AsyncManager across Action invocations?

I am new to asp.net mvc3. i am trying to implement an async controller. because of limitations of our codebase, i am constrained to using mvc3 (cannot use mvc4). I see that mvc3 provides an AsyncManager class. let's say Thread 0 creates instance of my controller and by extension instance of AsyncManager.

then the action method gets called concurrently:

Thread 1: t = 0s

public void ActionAsync()
{
   this.AsyncManager.Parameters["foo"] = "bar"; 
   // rest of code omitted - suppose it makes a http call to get some data
}

Thread 2: t = 0s

public void ActionAsync()
{
   this.AsyncManager.Parameters["foo"] = "spam"; // won't foo get overwritten?
   // rest of code omitted - suppose it makes a http call to get some data
}

Now when the completed method in response to the first call to ActionAsync gets called after 1s:

Thread 3: t = 1s

public ActionResult ActionCompleted(string foo)
{
   // won't foo become corrupted here?

}

i thought a unique instance of AsyncManager should be created and associated per call to an Action method, but looks like asp.net mvc3 creates an instance of AsyncManager per controller instance. how can it use same instance across concurrent action invocations?

Another situation: Thread 1 calls ActionAsync and makes a http call in that method and increments AsyncManager.OutstandingOperations. Simultaneously Thread 2 calls ActionAsync and makes a http call and increments AsyncManager.OutstandingOperations. after 1 s, first http call completes and AsyncManager.OutstandingOperations is decremented - but the ActionCompleted method will not get called since AsyncManager.OutstandingOperations will not be zero. clearly i am missing something

Upvotes: 2

Views: 86

Answers (1)

morpheus
morpheus

Reputation: 20380

Looks like i found answer to my question. A new instance of controller is created for every request per these links:
ASP.NET MVC: Is Controller created for every request?
ASP.NET MVC Controller Lifecycle

so there is a separate AsyncManager per call to an Action method.

Upvotes: 2

Related Questions