Every developer working on web applications eventually faces a common challenge: how to run background tasks. Whether it’s sending emails, processing files, cleaning up data, or generating reports, these tasks shouldn’t slow down your app or your users.
That’s where Hangfire steps in. Instead of creating complex custom threads or Windows services, Hangfire offers a simple, powerful, and flexible way to handle background tasks in .NET. You write your background code like any other method, and Hangfire handles the rest.
What is Hangfire?
Hangfire is an open-source library that enables you to perform background processing in .NET and .NET Core applications. You can enqueue long-running or scheduled tasks without blocking the main thread or freezing your app.
Key Features:
- No Windows Service or separate process required
- Persistent storage using databases (SQL Server, PostgreSQL, etc.)
- Built-in Dashboard to monitor tasks
- Retries, logging, and error handling built in
- Supports various job types (fire-and-forget, delayed, recurring)
In short, it’s background jobs made easy.
Why Use Hangfire?
Before we dive into code, let’s quickly see why Hangfire is a solid choice:
Ease of Use – No complex thread handling or task schedulers
Reliable – Jobs persist in storage (even after app restarts!)
Scalable – Works with small apps or big distributed systems
Secure Dashboard – Monitor jobs, retry failed ones, and see what’s happening behind the scenes
Flexible – From basic jobs to recurring CRON-based scheduling
Setting Up Hangfire in a .NET Application
Let’s break it down step-by-step.
Step 1: Install Hangfire via NuGet
bash
CopyEdit
Install-Package Hangfire
Install-Package Hangfire.SqlServer
Install-Package Hangfire.AspNetCore
If you’re using the .NET CLI:
bash
CopyEdit
dotnet add package Hangfire
dotnet add package Hangfire.SqlServer
dotnet add package Hangfire.AspNetCore
Step 2: Configure Hangfire in Startup.cs (for .NET Core)
Add Hangfire services and set up the dashboard and server.
csharp
CopyEdit
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(config =>
config.UseSqlServerStorage(Configuration.GetConnectionString(“DefaultConnection”)));
services.AddHangfireServer();
}
In the Configure method:
csharp
CopyEdit
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.. UseHangfireDashboard(); // Optional: enable dashboard at /hangfire
// other middleware
}
Types of Background Jobs in Hangfire
Hangfire supports several types of background jobs. Here’s a quick overview:
1. Fire-and-Forget Jobs
These are executed only once, immediately after being created.
csharp
CopyEdit
BackgroundJob.Enqueue(() => Console.WriteLine(“Fire-and-forget job executed!”));
2. Delayed Jobs
Execute a job after a specified time delay.
csharp
CopyEdit
BackgroundJob.Schedule(() => Console.WriteLine(“Delayed job!”), TimeSpan.FromMinutes(10));
3. Recurring Jobs
Run jobs on a recurring schedule using CRON expressions.
csharp
CopyEdit
RecurringJob.AddOrUpdate(
“my-recurring-job”,
() => Console.WriteLine(“Recurring job!”),
Cron.Daily);
4. Continuation Jobs
Run a job after another has completed.
csharp
CopyEdit
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine(“Initial job”));
BackgroundJob.ContinueWith(jobId, () => Console.WriteLine(“Continuation job”));
Using the Hangfire Dashboard
One of Hangfire’s best features is its built-in dashboard. Just visit:
bash
CopyEdit
http://localhost:5000/hangfire
From there, you can:
- See scheduled, running, and completed jobs
- Retry failed jobs
- Monitor queues
- View job history and logs
You can also protect the dashboard with authentication middleware to ensure only admins can access it.
csharp
CopyEdit
app.UseHangfireDashboard(“/hangfire”, new DashboardOptions
{
Authorization = new[] { new MyAuthorizationFilter() }
});
Real-Life Example: Sending Emails in the Background
Let’s say you want to send a welcome email after a user signs up. Instead of sending it directly, you can offload it to a Hangfire background job.
Step 1: Create the Job Method
csharp
CopyEdit
public class EmailService
{
public void SendWelcomeEmail(string email)
{
// Your email-sending logic here
Console.WriteLine($”Welcome email sent to {email}”);
}
}
Step 2: Enqueue the Job
csharp
CopyEdit
var emailService = new EmailService();
BackgroundJob.Enqueue(() => emailService.SendWelcomeEmail(“[email protected]”));
Simple, clean, and efficient.
Best Practices for Using Hangfire
Here are some tips to make the most of Hangfire:
- Keep your background jobs short and focused
- Avoid using HttpContext or anything that depends on a request
- Use dependency injection (DI) properly in job methods
- Store logs and errors for debugging
- Secure the Hangfire Dashboard in production
- Use queues to prioritise or segregate tasks
Error Handling and Retries
Hangfire automatically retries failed jobs a few times. You can customise this:
csharp
CopyEdit
[AutomaticRetry(Attempts = 3)]
public void SomeMethod()
{
// your logic
}
Or disable retries:
csharp
CopyEdit
[AutomaticRetry(Attempts = 0)]
Errors are logged and shown in the dashboard for easy tracking.
Advanced Features You Should Know
Here are a few more cool things Hangfire can do:
- Batch Jobs: Group multiple jobs together
- Job Filtering: Intercept jobs before/after execution (logging, metrics, etc.)
- Monitoring API: Use Hangfire’s API to build custom dashboards
- Job Queues: Assign jobs to specific queues for load balancing
- Integration with Serilog, NLog, and more
FAQs
Q1: Is Hangfire free to use?
Yes, Hangfire is free and open-source under the MIT license. There’s also a pro version with advanced features and support.
Q2: Can I use Hangfire with .NET 6+?
Absolutely! Hangfire supports .NET Framework, .NET Core, and .NET 5/6/7+.
Q3: Where are the jobs stored?
Jobs are stored in a persistent storage system. SQL Server is commonly used, but Hangfire also supports Redis, PostgreSQL, and others.
Q4: What happens if the server crashes?
Since jobs are stored in a database, Hangfire will pick up right where it left off when the app restarts. Nothing is lost.
Conclusion
Scheduling background tasks doesn’t need to be a nightmare. With Hangfire, you can effortlessly run, monitor, and manage background jobs right from your .NET application, without breaking a sweat.
From fire-and-forget to recurring CRON jobs, Hangfire’s flexible design makes it the go-to solution for background processing in NET. Plus, with a dashboard that gives you full visibility, you’re always in control.