What is AsyncManager.OutstandingOperations?

2019-06-16 08:52发布

Thanks to MSDN, they don't explain anything about it:

http://msdn.microsoft.com/en-us/library/system.web.mvc.async.asyncmanager.outstandingoperations(v=vs.108).aspx

Can somebody please explain AsyncManager.OutstandingOperations with a simple example?

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-16 09:13

It's basically a counter that you should increment at the beginning of each asyncrhonous operation and decrement at the end. You should ensure to decrement it even if the operations fails. The value of this counter must always be zero when all processing has finished.

Here's an article illustrating asynchronous controllers in ASP.NET MVC: http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx

查看更多
Viruses.
3楼-- · 2019-06-16 09:26

As far as I understand this is a replacement to web forms' SynchronizationContext in MVC world to guarantee that a thread processing the request will wait for all asynchronous operations to finish before returning. Consider the following code:

public ViewResult Index() { 
    Task.Factory.StartNew(() => {  // web service call here
    });
    return View();
}

Index() is running on the main (http request) thread. StartNew() will grab a thread from ThreadPool that starts running the web service call delegate on it and immediately returns to the main thread. The main thread immediately returns (a view) and finishes processing the request (somewhere down the stack inside ASP.NET runtime). But the second thread is still running (most likely waiting for I/O to complete) but that makes no sense - there is nobody waiting for it to consume its result.

That is what SynchronizationContext for in web forms. It keeps internal counter of all outstanding async calls and waits for all of them before returning from the main thread (i.e. the counter decrements to zero). AsyncManager does the same thing but you increment/decrement the counter manually. If you're interested in SynchronizationContext concept (not an easy thing to grasp) I'd recommend the series of articles by Mike Peretz. This one will also be very useful.

查看更多
登录 后发表回答