【发布时间】:2018-02-10 14:43:02
【问题描述】:
起初我以为这只是一个“How to wait for async method to complete?”问题。但是,我认为还不止于此。
我有一个这样设置的计时器......
public void Start()
{
_timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
_timer.Interval = _context.adpSettings.SyncInterval * 1000;
_timer.AutoReset = false;
_timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
var t = ExecuteTransactionReportAsync();
_timer.Start();
}
private async Task ExecuteTransactionReportAsync()
{
AccessEvent accessEvent = new AccessEvent();
.... do some logic
await _context.GetConnector().EnqeueuEventAsync(accessEvent);
}
我要做的是在ExecuteTransactionReportAsync() 完成之前不要让timer_Elapsed() 再次触发。但是,因为ExecuteTransactionReportAsync() 是异步的,所以进程会继续进行,timer_Elapsed() 将再次触发。
在现实生活中,ExecuteTransactionReportAsync() 完成任务的时间永远不会超过 10 秒。 (至少最好不要,否则我们还有其他问题。)但是当我调试时,这很痛苦。
是否有不涉及使ExecuteTransactionReportAsync() 非异步的简单解决方案?
【问题讨论】:
-
停止定时器,运行异步任务,在任务中添加
ContinueWith重启定时器? -
不要使用计时器,而是使用单线程循环,在循环结束时有延迟。
-
var t = await ExecuteTransactionReportAsync();?您必须使 eventHandler 异步才能使用它。 -
小修正:因为它是
async Task ExecuteTransactionReportAsync,所以必须没有var t =只是await ExecuteTransactionReportAsync() -
@Fildor,这是我尝试的第一件事。但随后它强制 Start() 中的调用也更改为等待,我无法让它工作
标签: c# asynchronous timer