I'm trying to fire off several HTTP requests from an ASP.NET page. The page itself doesn't need to know the response and should continue processing & deliver the page regardless.
I've tried putting the HTTP code in a BackgroundWorker and running it asynchronously, however I initially got the following error;
Asynchronous operations are not allowed in this context. Page starting an asynchronous operation has to have the Async attribute set to true and an asynchronous operation can only be started on a page prior to PreRenderComplete event.
So I did as I was told and gave the page the Async attribute. I then did some research and discovere开发者_开发知识库d that my BackgroundWorker isn't actually performing an asynchronous operation as I expected. Some background reading (http://www.pluralsight-training.net/community/blogs/mike/archive/2005/11/04/16213.aspx) informed me that;
PreRender and PreRenderComplete events [do] not resume until all of the timeout event handlers for all of the registered async tasks have been invoked and return.
How do I ensure that my BackgroundWorker does not suspend the processing of the page?
Another option to look at is ThreadPool.QueueUserWorkitem(). It will fire something off asynchronously. It will also use on of the threads in the asp.net threadpool.
I've typically used threadPool on the server and BackGroundWorker in gui/winforms. That's not to say it can't be done.
That's at least something else to try if you get stuck with BackgroundWorker...
Here's a few other SO posts:
ThreadPool.QueueUserWorkItem uses ASP.Net
ThreadPool.QueueUserWorkItem with a lambda expression and anonymous method
ThreadPool.QueueUserWorkItem with function argument
The new way to perform true async operations in ASP.NET is by using the PageAsyncTask class.(There's some sample code in the MSDN documentation)
Also, I recommend you read this post from Thomas Marquardt. The most interesting bit is this:
Ok, so you have a good reason to perform some work asynchronously, how should you do it? First of all, all of the code that you are able to run during the execution of a request must run within a module or handler. There is no other option. If you want work to be performed asynchronously—truly asynchronously, as in the current thread unwinds and execution of the request resumes only if and when your work completes—then you must run inside a module or handler that is asynchronous. If you don’t want to implement your own asynchronous module or handler, you’re in luck, because ASP.NET 2.0 introduced async pages , a feature which builds upon IHttpAsyncHandler and makes it easy to run asynchronous tasks known as PageAsyncTasks.
He also provides a code sample to perform async operations if chose not to use the PageAsyncTask
class.
精彩评论