如何安全配置一个System.Timers.Timer的? [英] How do I safely dispose a System.Timers.Timer?

查看:149
本文介绍了如何安全配置一个System.Timers.Timer的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你配置一个原始的.NET定时器,你可以通过在等待句柄调用一次在Win32计时器已经被破坏,你可以将它们假设你的回调将不会被调用。 (和计时器将被视为死,由GC)

When you dispose a "raw" .net timer, you can pass in a wait handle to be called once the Win32 timer has been destroyed and you can them assume that your call back will not be called. (And the timer will be considered "dead" by the GC)

我如何做一个System.Timers.Timer的?

How do I do this with a System.Timers.Timer?

推荐答案

正如System.Timers.Timer的和System.Windows.Forms.Timer都使用线程池它不具有手柄到操作系统的定时器,所以有是多数民众赞成处置没有原生的定时器资源 - 刚刚完成的线程。我不知道,你可以捕捉到一个线程被回收的线程池,但我可能是错的。

As System.Timers.Timer and System.Windows.Forms.Timer both use the ThreadPool it doesn't have a handle to an operating system timer, so there is no native timer resource that's disposed of - just a completed thread. I'm not sure you can capture a thread being recycled by the ThreadPool but I might be wrong.

您也许可以推出自己的(我没有测试过这一点,并采取了ManualResetEvent的处置中可能更有用):

You could maybe roll your own (I haven't tested this, and taking a ManualResetEvent in Dispose might be more useful):

void Run()
{
    ManualResetEvent resetEvent = new ManualResetEvent(false);

    System.Threading.Timer timer = new System.Threading.Timer(delegate { Console.WriteLine("Tick"); });
    timer.Dispose(resetEvent);

    MyTimer t = new MyTimer();
    t.Interval = 1000;
    t.Elapsed += delegate { t.Dispose(resetEvent); };

    resetEvent.WaitOne();
}


public class MyTimer : System.Timers.Timer
{
    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }

    public virtual void Dispose(WaitHandle handle)
    {
        handle.SafeWaitHandle.Close();
        Dispose();
    }
}

这篇关于如何安全配置一个System.Timers.Timer的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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