Recently I came across a requirement in a .Net Web API project to handle some time-consuming requests to another system which is beyond my control. Because of this users have to wait until the requests are completed. So to overcome this issue my team came up with implementing Hangfire; a cool open-source framework which is an easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications.
In this posts, I’m going to talk about the configuration and some features I used in my project but if you browse through the official site you can come across many other features in the Hangfire framework.
Hangfire has allowed developers to add Hangfire to projects through Manage NuGet Packages. Once you install Hangfire, two other depended packages will be installed to your project.
Configure Multiple Hangfire Servers
To configure Hangfire you need to do the following.
In Global.asax.cs file of you Web Api Project add the following code to Application_Start() method. By placing this code you will configure Hangfire and SQL Server. In my case, have to configure my Data Context.
Now we have to tell our application to initialize Hangfire. In Startup.cs add the following code to the Configuration(IAppBuilder app) method. This is where you have to specify the servers and queues you will be needing in your project.
In my user requirement, I need to create two servers with single queues with different worker counts. I have one queue in one server with one worker count and another with more than one worker counts. One server with sequential processing and one with multiple processing at a time.
Now I’ll show you how to use them in your code. Following code shows how to direct the method to be executed to the correct queue.
MethodToExcute() >>> Method that you are going to queue in Hangfire.
Hangfire has its own amazing dashboard where you can track the progress and the status of the tasks you have queued.
This is the two servers which were created from the above code.
These are some feature I used from Hangfire framework. More features can be used by you in your projects.