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.
- public class Worker
- {
- string filePath = @"d:/test.txt";
-
- public void StartProcessing(CancellationToken cancellationToken = default(CancellationToken))
- {
- try
- {
- if (File.Exists(filePath))
- File.Delete(filePath);
-
- using (File.Create(filePath)) { }
- using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath))
- {
- for (int index = 1; index <= 20; index++)
- {
-
- cancellationToken.ThrowIfCancellationRequested();
- file.WriteLine("Its Line number : " + index + "\n");
- Thread.Sleep(1500);
- }
-
- if (Directory.Exists(@"d:/done"))
- Directory.Delete(@"d:/done");
- Directory.CreateDirectory(@"d:/done");
- }
- }
- catch (Exception ex)
- {
- ProcessCancellation();
- File.AppendAllText(filePath, "Error Occured : " + ex.GetType().ToString() + " : " + ex.Message);
- }
- }
- private void ProcessCancellation()
- {
- Thread.Sleep(10000);
- File.AppendAllText(filePath, "Process Cancelled");
- }
- }
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".
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
-
- [HttpPost]
- public ActionResult Run(FormCollection form)
- {
- Response.Write("<h1>Application Stared</h1>");
- HostingEnvironment.QueueBackgroundWorkItem(cancellationToken => new Worker().StartProcessing(cancellationToken));
- Response.Write("<h3>Background Task Started...</h3>");
- Response.Write("<h1>Application Ended </h1>(Now You can close this application...)");
- return View();
- }
- }
Step 5
Create a submit in Index.cshtml.
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Index</title>
- </head>
- <body>
- @using (Html.BeginForm("Run", "Home", FormMethod.Post))
- {
- <input type="submit" value="Start Background Task" />
- }
- </body>
- </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...