views:

49

answers:

2

The Working with the BeginMethod/EndMethod Pattern section of Using an Asynchronous Controller in ASP.NET MVC refers to a Sync() method. It is not linked and I am having trouble finding documentation on it through google searches since sync is too common a term. Can someone point me in the write direction?

To make sure that you have access to the HttpContext.Current instance and to avoid the race condition, you can restore HttpContext.Current by calling Sync() from the callback method.

+1  A: 

It's a method of the AsyncManager class. http://msdn.microsoft.com/en-us/library/system.web.mvc.async.asyncmanager.sync.aspx

+1  A: 

When you spawn asynchronous operations by calling BeginXyz / EndXyz methods from within your controller action, the threads handling the asynchronous response are not under the control of ASP.NET. As such, you can't touch HttpContext, the controller instance, or any other shared state from within those threads. Calling the Sync() method basically synchronizes access to the request; it restores HttpContext.Current and grants you access to touch HttpContext, the controller, etc., but only for the duration of the Sync() call. The RegisterTask() extension method from MVC Futures attempts to make this a bit easier, as you basically pass it delegates to the target Begin and End methods, and the RegisterTask() helper will ensure that the End thread executes within an appropriate synchronization context.

If you're spawning asynchronous operations by calling XyzAsync / XyzCompleted methods from within your controller action, you don't have to worry about this, as the completed handler automatically runs within a synchronization context.

Levi