ThreadPool.QueueUserWorkItem in a web service for the Fire and Forget task

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

In a web service, I want to execute one method in another thread, for example, “Fire and Forget”, so that the web service returns some value in response immediately to the website. This method in another thread may take 10 minutes after the web service immediately returns a response to the website. In addition, I do not need to return the value of this method.

I tested this script with ThreadPool.QueueUserWorkItem, and it seems that the thread started using ThreadPool will still run even after the web service returns the response to the website. Will I fix it here? And is there a better way to achieve this?

+6
source share
1 answer

The problem is that from time to time ASP.NET will process the application pool. Since he does not know about your background task, he will not be considered and will be interrupted when the AppDomain is deleted.

In most cases, the work is completed, but if you run long enough, you will come across this scenario.

There are two solutions:

1) The "correct" way is to write a Windows service that runs outside of ASP.NET. You can send instructions to the service through WCF.

2) The “quick and dirty” way is to write a hidden web service on your ASP.NET site that is never called by users. Your application launches an asynchronous request to a hidden service and then returns its own result to the user without waiting.

ASP.NET does not know that a request for a hidden service comes from your application - it just treats it as another request. Because ASP.NET is aware of this request, it will not interrupt it when it is reused.

+6
source

Source: https://habr.com/ru/post/914046/


All Articles