簡體   English   中英

如何等待所有計時器任務完成?

[英]How to wait for all Timer Tasks to be done?

我有多個並行啟動的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
        )
    );
}

使用適合該工作的工具確實更好。 我建議使用微軟的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”。

正如@YacoubMassad在評論中指出的那樣,您的任務只是創建計時器並返回。

您可以做的是擺脫計時器並使用Task.Delay

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM