How to Execute Background Processing in By 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 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


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

There are some 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 the 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.


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

Want to Create a Web Application?

Book your free consultation with web app experts.

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

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

        PM > Install-Package HangFire

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

👉 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(; // Enqueue Send Email
        BackgroundJob.Enqueue(() => SendSms(; // 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 MVC Web API using HangFire. 

Download the source code of this project, Here.

Author Bio
Jigar Mistry
Jigar Mistry
Designation: Vice President (Technologies)

Jigar Mistry is Vice President (Technologies) at Space-O Technologies. He has 14+ years of experience in the web and mobile app development industry. He has expertise in different mobile app categories like health and fitness, eCommerce, and on-demand.