Sure! Here's an example of how to use Hangfire in an ASP.NET Web Forms application:
Step 1: Create a new ASP.NET Web Forms project in Visual Studio.
Step 2: Install the Hangfire package via NuGet. Open the Package Manager Console and run the following command:
Install-Package Hangfire
Step 3: Create a new class file called "HangfireConfig.cs" and add the following code:
using Hangfire;
public class HangfireConfig
{
public static void ConfigureHangfire()
{
GlobalConfiguration.Configuration.UseSqlServerStorage("YourConnectionString"); // Replace with your connection string
var options = new BackgroundJobServerOptions
{
Queues = new[] { "default", "myqueue" }, // Add any custom queues you want to use
WorkerCount = 1 // Number of workers to process background jobs
};
using (var server = new BackgroundJobServer(options))
{
// Start the Hangfire server
}
}
}
Step 4: In the Global.asax file, add the following code:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
HangfireConfig.ConfigureHangfire();
}
Step 5: Create a new ASPX page called "Default.aspx" and add a button control to it:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="HangfireExample._Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnScheduleJob" runat="server" Text="Schedule Job" OnClick="btnScheduleJob_Click" />
</div>
</form>
</body>
</html>
Step 6: In the code-behind file "Default.aspx.cs", add the following code:
using Hangfire;
namespace HangfireExample
{
public partial class _Default : System.Web.UI.Page
{
protected void btnScheduleJob_Click(object sender, EventArgs e)
{
Hangfire.BackgroundJob.Enqueue(() => ProcessJob()); // Schedule the background job
}
public void ProcessJob()
{
// Code to be executed in the background
System.Threading.Thread.Sleep(5000); // Simulate some long-running operation
System.Diagnostics.Debug.WriteLine("Background job executed!");
}
}
}
That's it! Now, when you run the application and click the "Schedule Job" button on the Default.aspx page, a background job is enqueued and processed by Hangfire.
Note: Make sure you have a valid SQL Server connection string in the ConfigureHangfire method in the HangfireConfig.cs file. Additionally, you may need to install the necessary Hangfire storage NuGet package (e.g., Hangfire.SqlServer) based on your chosen storage backend.