在 Hangfire 中,BackgroundJob.Enqueue 和 new BackgroundJobClient() 都是用来添加后台作业的方法。它们之间的主要区别如下:
下面是一些使用示例:
使用 BackgroundJob.Enqueue 提交一个后台作业:
// Basic usage
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
// With arguments
BackgroundJob.Enqueue(() => SendEmail("alice@example.com", "Hello from Hangfire!"));
// With delay
BackgroundJob.Schedule(() => Console.WriteLine("Hello, from the past!"), TimeSpan.FromDays(7));
使用 new BackgroundJobClient() 类的实例来提交一个后台作业:
// Basic usage
var client = new BackgroundJobClient();
client.Enqueue(() => Console.WriteLine("Hello, world!"));
// With arguments
var client = new BackgroundJobClient();
client.Enqueue(() => SendEmail("alice@example.com", "Hello from Hangfire!"));
// With parameters
var client = new BackgroundJobClient();
client.Create().With(x => x.CustomerId = 123).Enqueue();
// With delay
var client = new BackgroundJobClient();
client.Schedule(() => Console.WriteLine("Hello, from the past!"), TimeSpan.FromDays(7));