通过计时器写入数据库的后台任务

bla*_*cat 4 c# async-await asp.net-core asp.net-core-2.1 asp.net-core-hosted-services

如何在后台的计时器上写入数据库。例如,检查邮件并将新字母添加到数据库。在示例中,我在写入数据库之前简化了代码。

Microsoft示例中的类名称。录音课本身:

namespace EmailNews.Services
{

internal interface IScopedProcessingService
{
    void DoWork();
}

internal class ScopedProcessingService : IScopedProcessingService
{
    private readonly ApplicationDbContext _context;
    public ScopedProcessingService(ApplicationDbContext context)
    {
        _context = context;
    }

    public void DoWork()
    {
        Mail mail = new Mail();
        mail.Date = DateTime.Now;
        mail.Note = "lala";
        mail.Tema = "lala";
        mail.Email = "lala";
        _context.Add(mail);
        _context.SaveChangesAsync();
    }
}
}
Run Code Online (Sandbox Code Playgroud)

计时器类:

namespace EmailNews.Services
{
#region snippet1
internal class TimedHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private Timer _timer;

    public TimedHostedService(IServiceProvider services, ILogger<TimedHostedService> logger)
    {
        Services = services;
        _logger = logger;
    }
    public IServiceProvider Services { get; }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is starting.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero,
            TimeSpan.FromMinutes(1));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        using (var scope = Services.CreateScope())
        {
            var scopedProcessingService =
                scope.ServiceProvider
                    .GetRequiredService<IScopedProcessingService>();

            scopedProcessingService.DoWork();
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)

启动:

        services.AddHostedService<TimedHostedService>();
        services.AddScoped<IScopedProcessingService, ScopedProcessingService>();
Run Code Online (Sandbox Code Playgroud)

似乎一切都像示例中那样完成,但是什么都没有添加到数据库中,不是吗?

Pan*_*vos 5

这是一个非常有趣的问题,可以归结为“如何正确处理异步计时器回调?”

眼前的问题是SaveChangesAsync没有等待。DbContext几乎肯定会在SaveChangesAsync有机会运行之前被处置。为了等待它,DoWork必须成为一个async Task方法(永远不要异步作废):

internal interface IScheduledTask
{
    Task DoWorkAsync();
}

internal class MailTask : IScheduledTask
{
    private readonly ApplicationDbContext _context;
    public MailTask(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task DoWorkAsync()
    {
        var mail = new Mail 
                   { Date = DateTime.Now,
                     Note = "lala",
                     Tema = "lala",
                     Email = "lala" };
        _context.Add(mail);
        await _context.SaveChangesAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在的问题是如何DoWorkAsync从计时器回调中调用。如果我们不等待就直接调用它,那么我们将遇到最初遇到的相同问题。计时器回调无法处理返回Task的方法。我们也不能做到这一点async void,因为这将导致相同的问题-该方法将在任何异步操作有机会完成之前返回。

David Fowler在其Async Guidance 文章的Timer Callbacks部分中说明了如何正确处理异步计时器回调:

private readonly Timer _timer;
private readonly HttpClient _client;

public Pinger(HttpClient client)
{
    _client = new HttpClient();
    _timer = new Timer(Heartbeat, null, 1000, 1000);
}

public void Heartbeat(object state)
{
    // Discard the result
    _ = DoAsyncPing();
}

private async Task DoAsyncPing()
{
    await _client.GetAsync("http://mybackend/api/ping");
}
Run Code Online (Sandbox Code Playgroud)

实际方法应该是,async Task但是返回的任务只需分配即可,而不必等待,以使其正常工作。

将其应用于问题会导致如下结果:

public Task StartAsync(CancellationToken cancellationToken)
{
    ...
    _timer = new Timer(HeartBeat, null, TimeSpan.Zero,
        TimeSpan.FromMinutes(1));

    return Task.CompletedTask;
}

private void Heartbeat(object state)
{
    _ = DoWorkAsync();
}


private async Task DoWorkAsync()
{
    using (var scope = Services.CreateScope())
    {
        var schedTask = scope.ServiceProvider
                             .GetRequiredService<IScheduledTask>();

        await schedTask.DoWorkAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

大卫·福勒(David Fowler)解释了为什么异步无效在ASP.NET Core中始终错误的 -不仅不等待异步操作,而且异常还会使应用程序崩溃。

他还解释了为什么我们不能使用 Timer(async state=>DoWorkAsync(state)) -这是一个async void委托。