等待System.Threading.Timer回调退出程序前完成 [英] Wait for System.Threading.Timer Callbacks to Complete before Exiting Program

查看:665
本文介绍了等待System.Threading.Timer回调退出程序前完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表与LT; System.Threading.Timer> 。每个定时器触发在配置的间隔(默认为10分钟)。所有调用相同的回调方法(使用不同的参数)。回调方法可能需要几秒钟才能完成它的工作。

I have a List<System.Threading.Timer>. Each Timer fires at a configurable interval (default 10 minutes). All call the same callback method (with a different parameter). The callback method can take several seconds to complete it's work.

在程序终止,它看起来像回调方法的执行立即停止(我看到这是否正确? )。

When the program terminates, it looks like execution of the callback method is immediately halted (am I seeing that correctly?).

我怎样才能优雅地等待任何当前执行的回调方法退出程序前完成?

How can I elegantly wait for any currently-executing callback methods to complete before exiting the program?

推荐答案

您可以用处置参数WaitHandler所有定时器。当完成回调方法该处理器将只发出信号(如规范说:计时器没有设置,直到所有当前排队的回调已经完成)

You can Dispose all timers with WaitHandler parameter. This handler will be signaled only when callback method is completed (as spec says: "The timer is not disposed until all currently queued callbacks have completed.")

void WaitUntilCompleted(List<Timer> myTimers)
{
    List<WaitHandle> waitHnd = new List<WaitHandle>();
    foreach (var timer in myTimers)
    {
        WaitHandle h = new AutoResetEvent(false);
        timer.Dispose(h);
        waitHnd.Add(h);
    }
    WaitHandle.WaitAll(waitHnd.ToArray());
}

这篇关于等待System.Threading.Timer回调退出程序前完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆