Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadPool.QueueUserWorkItem in Web Service for “Fire and Forget” task

This is ASP.NET ASMX Web Service / .NET Framework 4.0.

In web service, I want to execute one method on another thread something like “Fire and Forget” so that Web Service returns some value in response immediately to web site. That method on another thread could take 10 minutes after Web Service returns response immediately to Web site. Also, I do not need return value of that method.

I have tested this scenario using ThreadPool.QueueUserWorkItem and it seems that thread started using ThreadPool will still keep executing even after Web Service returns response back to Web site. Am I correct here? Also is there a better way to achieve this?

like image 306
mahesh Avatar asked Apr 24 '12 14:04

mahesh


1 Answers

The problem is that every now and then, ASP.NET will recycle the app pool. Because it doesn't know about your background task, it will not be considered and will be aborted when the AppDomain is disposed.

Most of the time, the work will complete, but if you run for long enough, you will encounter this scenario.

There are two solutions:

1) The "proper" way is to write a Windows Service that runs outside ASP.NET. You can send instructions to the Service over WCF.

2) The "quick and dirty" way is to write a hidden web service in your ASP.NET site that is never called by users. Your app starts an asynchronous request to the hidden service and then returns its own result to the user, without waiting.

ASP.NET does not know that the request to the hidden service came from inside your app - it just treats it as another request. Because ASP.NET knows about this request, it will not abort it when it recycles.

like image 96
Nick Butler Avatar answered Oct 13 '22 00:10

Nick Butler