我正在使用 .Net-Core 编写一个托管服务,它基于定时器在后台运行任务。
目前我必须像这样同步运行代码:
public override Task StartAsync(CancellationToken cancellationToken)
{
this._logger.LogInformation("Timed Background Service is starting.");
this._timer = new Timer(ExecuteTask, null, TimeSpan.Zero,
TimeSpan.FromSeconds(30));
return Task.CompletedTask;
}
private void ExecuteTask(object state)
{
this._logger.LogInformation("Timed Background Service is working.");
using (var scope = _serviceProvider.CreateScope())
{
var coinbaseService = scope.ServiceProvider.GetRequiredService<CoinbaseService>();
coinbaseService.FinalizeMeeting();
}
}
我希望能够在定时器上异步运行代码,但我不想使用fire and forget方式异步运行代码,因为这可能会导致我的代码出现竞争条件。
例如(订阅timer.Elapsed
事件)
有没有一种方法可以利用异步代码来进行定时调度而不执行fire and forget呢?
private async Task ExecuteTask(object state)
呢? - zaitsman