How to Perform Background Processing in asp.net using HangFire?

0
Shares
How to Perform Background Processing in asp.net using HangFire?
5 (100%) 2 votes

how to perform background processing in asp.net using HangFire

Suppose, you have an application through which you can send mail to multiple recipients. However, sometimes, it loads much to complete a particular task and you have to wait longer.

To minimize loading time and longer waits, we come up with one solution that processes tasks in a background so users can switch to another task with ease.

There are many apps available to send messages in bulk without waiting for the process to complete and perform further operations. A lot of great ways available to do things in the background and many libraries are available to hide loading time.

I wonder is it possible to run a long running task on an ASP.net?

Yes.

At some point, you have to launch background tasks on an ASP.net application, either by analyzing, manipulating or consolidating data from a database to edit pictures, send newsletters or anything else.

There are some asp.net apps hosted in IIS in the data center, and others are in the Azure cloud. In my opinion, Hangfire or similar open source libraries work best to write background tasks in the ASP.NET website.

In this post, we have pointed some common gotchas that usually developers found when they work in the background.

  • An unhandled exception in a thread not connected with a request will take down the process.
  • The AppDomain your site runs in can go down for a number of reasons and take down your background task with it.
  • If you run your site in a Web Farm, you could end up with multiple instances of your app that all effort to run the same task at the same time.

Let me share an example with you

We are developing security application for our client. He wanted to send email/SMS to multiple recipients when any user is in danger. We recommended him two solutions:

Solution #1 (Not Recommended)

We can send email/SMS to all recipients by looping over their Phone Numbers/Emails. With this solution, the issue is that the process of the loop will continue running until the code finishes and users also have to wait for the response. This will hang the entire app and also user’s device, which not good practice.

Solution #2 (HangFire Recommended)

HangFire is a free and open source tool that allows operations like fire-and-forget, delayed and recurring tasks inside ASP.NET applications. Also, it doesn’t require Windows Service or any separate process.

Prerequisites

  • .NET Framework 4.5
  • Persistent storage 
  • Newtonsoft.Json library ≥ 5.0.1

Job Storage

Hangfire uses persistent storage to keep background jobs and other information that relates to the processing.

Below storage backends are supported(Persistent Storage):

We have used SqlServer as Job Storage with HangFire

Following are the Steps required to install HangFire

Step 1:

Run the following command in the Package Manager Console in your Asp.net application, where you want to add HangFire

        PM > Install-Package HangFire

After running above command, HangFire will install all its required libraries and packages.

Step 2:

After HangFire is installed, we need to create HangFire client to use HangFire in Code. For that, you have to write down below code in your API.

In Global.asax.cs File:

using Hangfire; // Include Namespace required for HangFire

using Hangfire.SqlServer; //As we have used SqlServer as Job Storage for HangFire include this Namespace

private BackgroundJobServer _backgroundJobServer; // declare BackGroundJoberver Object

In Application_Start() Event

protected void Application_Start()
       {
                      var storage = new SqlServerStorage(System.Configuration.ConfigurationManager.ConnectionStrings["db_HangFire"].ConnectionString); // db_HangFire is the connection string for Sql Server DB used as Job Storage for HangFire for processing 
 
           var options = new BackgroundJobServerOptions();
 
           var _backgroundJobServer = new BackgroundJobServer(options, storage);
           _backgroundJobServer.Start(); // start BackgroundJobServer process
           JobStorage.Current = storage; // assign the storage to Current
 
       }

In Application_End() Event

protected void Application_End(object sender, EventArgs e)
       {
           _backgroundJobServer.Dispose(); // Dispose the BackgroundJobServer Object
       }

In WebApi Controller, where you want to send Email/SMS in background

public HttpResponseMessage PostTest(model)
{
      	BackgroundJob.Enqueue(() => SendEmail(model.email)); // Enqueue Send Email
      	BackgroundJob.Enqueue(() => SendSms(model.phone)); // Enqueue Send Sms
}
 
Public void SendEmail(email)
{
        	// Email sending logic
}
 
Public Void SendSms(phone)
{
        	// Sms sending logic
}

You can also see the entire logs in the HangFire DB, which is in SqlServer. You can also see HangFire Documentation for more information.

Hope, you will find this tutorial helpful to implement bulk emails in a background in asp.net MVC Web API using HangFire. 

If you want to download the source code of this project, click on the following button.

 
0
Shares
 

LET'S TALK VALIDATE YOUR IDEA!