与计时器异步

时间:2014-09-28 16:18:16

标签: c# asynchronous timer

我更新我的代码以使用Async,问题是Timer.Elapsed需要一个void返回类型,但这基本上不允许等待,所以代码不会一切都完成之前,等待并完成。

代码:

public static void Main(string[] args)
{
   Timer timer;

   timer = new System.Timers.Timer();
   timer.Interval = 3000;
   timer.Elapsed += OnTimerAsync;
   timer.Enabled = true;
   timer.Start();

   Console.WriteLine("Press the Enter key to exit the program... ");
   Console.ReadLine();
   Console.WriteLine("Terminating the application...");
}

public async static void OnTimerAsync(object sender, ElapsedEventArgs args)
{
   await ExecuteWorkflowAsync();
}

private async static Task<bool> ExecuteWorkflowAsync()
{
   List<Schedule> schedulesToRun;

   try
   {
      await JobLoader.LoadAsync(schedulesToRun);
   }
   catch (Exception ex)
   {
       // Log ex
   }

  return true;
}

有没有办法将Timer对象与Async一起使用?

1 个答案:

答案 0 :(得分:0)

试试这个:

public async static void OnTimerAsync(object sender, ElapsedEventArgs args)
{
   timer.Enabled = false;
   await ExecuteWorkflowAsync();
   timer.Enabled = true;
}