Pattern nào là đúng để thực hiện công việc nền dài hạn trong Asp.Net Core?
Pattern nào là đúng để thực hiện công việc nền dài hạn trong Asp.Net Core?
Mẫu chuẩn: IHostedService / BackgroundService chạy trong Generic Host, kết hợp hàng đợi và scope cho từng công việc.
public class QueueWorker(IBackgroundTaskQueue queue, IServiceScopeFactory sf) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
await foreach (var work in queue.DequeueAllAsync(ct))
{
using var scope = sf.CreateScope();
await work(scope.ServiceProvider, ct);
}
}
}
builder.Services.AddHostedService<QueueWorker>();
builder.Services.AddSingleton<IBackgroundTaskQueue, ChannelTaskQueue>(); // System.Threading.Channels
| Nhu cầu | Giải pháp |
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.