Hangfire for C# (.NET): Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

What is Hangfire and why is it needed?

\n\n

Hangfire is a powerful and popular library for C# (.NET) designed for executing background jobs. In modern web development, there is often a need to perform operations that should not block the main execution thread of the application. For example: sending email notifications, generating reports, processing uploaded files, synchronizing data with external APIs, cleaning up outdated database records, and much more.

\n\n

Hangfire provides a simple yet flexible way to run such tasks. Key features of the library:

\n
    \n
  • Background job execution: Tasks run asynchronously without blocking the user response.
  • \n
  • Scheduling: You can run tasks on a schedule (cron expressions) or with a delay.
  • \n
  • Reliability: Hangfire stores job information in persistent storage (database). Even if the application restarts, unfinished jobs will be executed.
  • \n
  • Monitoring: Built-in web interface (Dashboard) allows you to track job status, view logs, and retry failed jobs.
  • \n
  • Retries: If a job fails with an error, Hangfire automatically attempts to execute it again (with a configurable retry policy).
  • \n
  • DI Integration: Easily integrates with Dependency Injection containers in ASP.NET Core.
  • \n
\n\n

Hangfire supports various storage options: SQL Server, PostgreSQL, Redis, MongoDB, and others. This makes it suitable for projects of any scale — from small websites to high-load enterprise systems.

\n\n

Installation

\n\n

Hangfire is installed via NuGet Package Manager. Unlike Python, where pip install is used, the .NET ecosystem uses dotnet add package or the Visual Studio package manager.

\n\n

To install the base Hangfire package, run the following command in the terminal (in your project's root folder):

\n\n
dotnet add package Hangfire
\n\n

This command installs the Hangfire core and dependencies for in-memory job storage (InMemory). For a production environment, you will need to install a package for a specific database, for example:

\n\n
    \n
  • SQL Server: dotnet add package Hangfire.SqlServer
  • \n
  • PostgreSQL: dotnet add package Hangfire.PostgreSql
  • \n
  • Redis: dotnet add package Hangfire.Redis
  • \n
\n\n

After installing the packages, you need to configure Hangfire in the Program.cs file (for ASP.NET Core) or Startup.cs.

\n\n

Quick Start

\n\n

Let's look at a minimal example of setting up and using Hangfire in an ASP.NET Core application.

\n\n

Step 1: Configuration in Program.cs

\n\n
using Hangfire;\nusing Hangfire.SqlServer;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Adding Hangfire with SQL Server storage\nbuilder.Services.AddHangfire(configuration => configuration\n    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)\n    .UseSimpleAssemblyNameTypeSerializer()\n    .UseRecommendedSerializerSettings()\n    .UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection")));\n\n// Adding Hangfire server\nbuilder.Services.AddHangfireServer();\n\nvar app = builder.Build();\n\n// Enabling the Dashboard\napp.UseHangfireDashboard();\n\n// Example of a simple background job\napp.MapGet("/fire-and-forget", () =>\n{\n    var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Hello from Hangfire!"));\n    return $"Job {jobId} has been enqueued.";\n});\n\napp.Run();
\n\n

Step 2: Creating a Job

\n

In the example above, we used the method <

Recommendations