Giải thích việc sử dụng lớp BackgroundService trong Asp.Net Core?
Giải thích việc sử dụng lớp BackgroundService trong Asp.Net Core?
BackgroundService là lớp cơ sở trừu tượng cài đặt IHostedService, giúp viết dịch vụ nền chạy lâu dài chỉ bằng cách ghi đè ExecuteAsync.
public class CleanupWorker(IServiceScopeFactory sf, ILogger<CleanupWorker> log) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(5));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
using var scope = sf.CreateScope();
var svc = scope.ServiceProvider.GetRequiredService<ICleanupService>();
await svc.RunAsync(stoppingToken);
Đă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.