In my application, I want to run a time consuming long process in a one web request.
At the begining, I used to call a web api method to run that process. But it didn’t work. Since the process takes long time to complete its action, request is getting hanged.
We can work on few options to resolve this,
- We can create a windows service to run this process, It’s a seperate process from the web request. We can periodically check whether action is completed or not until action gets completed, We can install this service in our local pc or server
- Windows service installed in Azure worker role, If we want to host the windows service in cloud environment, we can host the service in azure worker role.
- We can use a seperate thread to process the log runing action
In my solution, I used to create a background worker process to handle the long running task.
If we have to use a seperate thread to run a time consuming action, We can use Web backgrounder third party package. It’s going to run a background process in specific intervals. When the task gets completed, it’s going to automatically kill the background process.
Let’s see the code in action!!!
First of all, install the web background worker third party library into the project.
This code snippet shows how to initialise a job and how to perform a action on it,
I refered to the above code snippet and created a specific worker thread according to my requirements.
actual implementation of worker thread is shown below. Worker class should inherit from IDisposable interface.
In the constructor of the worker class, specify the time interval and then call long running action in a seperate thread.
Dispose() method is getting called when process is completed.
I call this worker process inside a web api controller. Create a private static variable and initialise it with worker class constructor.
note : I added log messages to identify starting point and end point of the worker process, Here is a sample of that log.
Until the task is getting completed, worker thread runs. It’s going to complete the process in second interval. When the task is completed, it’s going to dispose the worker thread.