Run Background Task In Web Apps Using QueueBackgroundWorkItem

Introduction

In this article, we will learn how to keep running our task after closing the web application. A user does not have to stay on the application. We will demonstrate this easily by HostingEnvironment API. 
 
What is HostingEnvironment API?

HostingEnvironment API was announced in .NET Framework 4.5.2. Now, it’s very easy to run background jobs in ASP.NET Web application. HostingEnvironment API allows us to queue background jobs like thread pool and avoids IIS app pools shutdown until the tracked tasks are completed. 

When to use it

When you have long running task which is taking too much time to complete and the user has to wait until it’s not completed, in this situation, you can use this feature. After implementing this, the user will start that task and he/she will close the application within a second after the start. Here the awesome thing is that the task will complete by itself in the background.

Note

This feature is only available after .Net Framework 4.5.2. So you have to choose that type of web application.

QueueBackgroundWorkItem syntax
 
The QueueBackgroundWorkItem method has two overloads, each of which accepts a single parameter. You can pass either of the following,
  • Action<CancellationToken>
  • Func<CancellationToken, Task>

Example

Let us see a small demo MVC application of this feature which generates 1 to N numbers and writes to a file in the background. You can follow steps or download the source code from above link.
 
Step 1

Open Visual Studio, Add a new project of ASP.NET Web Application with .Net Framework 4.5.2
 
 
 
Step 2

Select an Empty template and MVC type of project.
 
 
 
After creating the project, you will see something like the below folder structure.
 
 
 
Step 3
 
Add a new class in any folder of the project ( I named it "Worker.cs";) and paste the below code for two  methods.
  1. public class Worker  
  2. {  
  3.     string filePath = @"d:/test.txt";  
  4.   
  5.     public void StartProcessing(CancellationToken cancellationToken = default(CancellationToken))  
  6.     {  
  7.         try  
  8.         {  
  9.             if (File.Exists(filePath))  
  10.                 File.Delete(filePath);  
  11.   
  12.             using (File.Create(filePath)) { }  
  13.             using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))  
  14.             {  
  15.                 for (int index = 1; index <= 20; index++)  
  16.                 {  
  17.                     //execute when task has been cancel  
  18.                     cancellationToken.ThrowIfCancellationRequested();  
  19.                     file.WriteLine("Its Line number : " + index + "\n");  
  20.                     Thread.Sleep(1500);   // wait to 1.5 sec every time  
  21.                 }  
  22.   
  23.                 if (Directory.Exists(@"d:/done"))  
  24.                     Directory.Delete(@"d:/done");  
  25.                 Directory.CreateDirectory(@"d:/done");  
  26.             }  
  27.         }  
  28.         catch (Exception ex)  
  29.         {  
  30.             ProcessCancellation();  
  31.             File.AppendAllText(filePath, "Error Occured : " + ex.GetType().ToString() + " : " + ex.Message);  
  32.         }  
  33.     }  
  34.     private void ProcessCancellation()  
  35.     {  
  36.         Thread.Sleep(10000);  
  37.         File.AppendAllText(filePath, "Process Cancelled");  
  38.     }  
  39. }  
 
 
Step 4
 
Add new Controller named Home Controller and make two methods, the first one is for Get (page load) named "Index" and the second one is for Post (After Submit Of Form) named "Run".
  1. public class HomeController : Controller  
  2. {  
  3.     public ActionResult Index()  
  4.     {  
  5.         return View();  
  6.     }  
  7.   
  8.     [HttpPost]  
  9.     public ActionResult Run(FormCollection form)  
  10.     {  
  11.         Response.Write("<h1>Application Stared</h1>");  
  12.         HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => new Worker().StartProcessing(cancellationToken));  
  13.         Response.Write("<h3>Background Task Started...</h3>");  
  14.         Response.Write("<h1>Application Ended </h1>(Now You can close this application...)");  
  15.         return View();  
  16.     }  
  17. }  
 
 
Step 5
 
Create a submit in Index.cshtml.
  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <!DOCTYPE html>  
  6.   
  7. <html>  
  8. <head>  
  9.     <meta name="viewport" content="width=device-width" />  
  10.     <title>Index</title>  
  11. </head>  
  12. <body>  
  13.     @using (Html.BeginForm("Run", "Home", FormMethod.Post))  
  14.     {  
  15.         <input type="submit" value="Start Background Task" />  
  16.     }  
  17. </body>  
  18. </html>  
 
 
Step 6
 
Run the application and Click on "Start Background Task" button.
 
 
 
Step 7
 
After loading the new page close that application at the same moment. It will take some time to generate numbers and write it to a file.
 
  
 
Step 8
 
That's it... After a few seconds you can see demo.txt file in given path and application will generate "done" folder after completion of task to make sense.
 
 

Conclusion

We have seen HostingEnvironment.QueueBackgroundWorkItem of .Net Framework 4.5.2 to make background running web application. Feel free to ask me any questions related to this article.

Thank You For Reading...

Up Next
    Ebook Download
    View all
    Learn
    View all