【发布时间】:2015-10-14 19:17:52
【问题描述】:
我目前正在从事一个项目,我想在后台执行一些定期更新,并且我想通过 System.Threading.Timer 使用 async/await 来实现此目的。我找不到任何关于这个特定主题的文章。
以下 sn-p 有效。我只是不确定使用返回 void 的异步方法应该只用于事件处理程序,如按钮单击。下面的代码中是否存在“违反”最佳实践的内容?
public class ScheduledCache
{
private CancellationTokenSource _cancelSource = new CancellationTokenSource();
private Request _request = new Request();
private Timer _timer;
public void Start()
{
_cancelSource = new CancellationTokenSource();
_timer = new Timer(UpdateAsync, null, 2000, Timeout.Infinite);
}
public void Stop()
{
_cancelSource.Cancel();
}
public async void UpdateAsync(object state)
{
try
{
await Task.WhenAll(UpdateSomethingAsync(_cancelSource.Token), UpdateSomethingElseAsync(_cancelSource.Token));
}
catch (OperationCanceledException)
{
// Handle cancellation
}
catch (Exception exception)
{
// Handle exception
}
finally
{
if (_cancelSource.IsCancellationRequested)
_timer = new Timer(UpdateAsync, null, 2000, Timeout.Infinite);
else
_timer = new Timer(UpdateAsync, null, Timeout.Infinite, Timeout.Infinite);
}
}
private async Task UpdateSomethingAsync(CancellationToken cancellationToken)
{
await Task.Run(new Action(_request.UpdateSomething));
}
private async Task UpdateSomethingElseAsync(CancellationToken cancellationToken)
{
await Task.Run(new Action(_request.UpdateSomethingElse));
}
}
public class Request
{
public void UpdateSomething()
{
// Do some updates here
}
public void UpdateSomethingElse()
{
// Do some other updates here
}
}
【问题讨论】:
标签: c# multithreading asynchronous timer async-await