如何等待所有计时器任务完成?

时间:2017-09-14 08:28:46

标签: c# multithreading timer

我有多个System.Threading.Timer并行启动。最后,我有一个Task.Wait等待所有任务完成。但它并不等待所有,我怎么能让它等待所有人呢?

private List<Task> todayTasks = new List<Task>();

foreach (var item in todayReport)
{
    todayTasks.Add(SetupTimer(item.Exec_Time, item.Report_Id));            
}

Task.WaitAll(todayTasks.ToArray());

- SetupTimer--

private Task SetupTimer(DateTime alertTime, int id)
{
    DateTime current = DateTime.Now;
    TimeSpan timeToGo = alertTime.TimeOfDay - current.TimeOfDay;

    if (timeToGo < TimeSpan.Zero) {
        //TODO: ERROR time already passed
    }

    ExecCustomReportService executeCustom = new ExecCustomReportService();

    return Task.Run(
        () => new Timer(
            x => executeCustom.AdhockReport(id), null, timeToGo, Timeout.InfiniteTimeSpan
        )
    );
}

2 个答案:

答案 0 :(得分:0)

你最好使用适合这项工作的工具。我建议微软的Reactive Framework(Rx)。然后你可以这样做:

var query =
    from item in todayReport.ToObservable()
    from report in Observable.Start(() => executeCustom.AdhockReport(item.Report_Id))
    select report;

IDisposable subscription =
    query
        .Subscribe(
            report =>
            {
                /* Do something with each report */
            },
            () =>
            {
                /* Do something when finished */
            });

你只需要NuGet“System.Reactive”。

答案 1 :(得分:-1)

正如@YacoubMassad在评论中所说,你的任务只是创建计时器并返回。

你可以做的是摆脱计时器并使用Task.Delay

return Task.Delay(timeToGo).ContinueWith(t=> executeCustom.AdhockReport(id));