System.Timers.Timer生命周期 [英] System.Timers.Timer lifecycle

查看:255
本文介绍了System.Timers.Timer生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种是使用System.Timers.Timer的正确方法?
我的意思是...我创建计时器,设置间隔和在Elapsed事件上要调用的方法。

which is the right approach to use a System.Timers.Timer? I mean... I create the timer, set the interval and the method to be called on the Elapsed event.

double ms = 1000;
var t = new System.Timers.Timer(ms);
t.AutoReset = false;
t.Elapsed += (sender, e) =>  { runTask(); }; 
t.Start();   

接下来要做什么?计时器上应该打个电话吗?我想我做不到,否则Elapsed事件将永远不会发生。
我应该在某个全局变量中注册Timer以避免丢失对它的引用,以便GC可以在调用Elapsed之前处置该Timer吗?
如果是这样,一旦处理了Elapsed事件(因此我的任务已执行),我该如何处置计时器?

What next? Should a call dispose on the Timer? I suppose I can't, or the Elapsed event will never occur. Should I register the Timer in some global variable to avoid to lose references to it and so the GC could dispose the timer before the Elapsed is called? And if so, how can I dispose the Timer once the Elapsed event has been handled (thus my task has been executed)?

推荐答案

一个简单的答案是您不需要执行任何操作。当功能超出范围时,它将由垃圾收集器收集。如果您希望它可用,请改为在类中声明它。



通常,当您在类级别声明定时器时,GC将在处置该类时将其收集。但是,当您在函数中声明计时器时,计时器仍会运行,但是如果执行的过程很长,则GC可以积极地处置它,因此您需要使用

A short answer is you don't need to do anything. It will be collected by the Garbage Collector when function goes out of scope. If you want it available then declare it in class instead.


Usually when you declare a timer out in class level it is collected by GC when the Class is Disposed. However when you have your timer declare in a Function then the Timer still runs but if you are executing a very long process then GC can Aggressively Dispose it so you will need to use

GC.KeepAlive(youtimer_Instance);

看看计时器的文档 n,以供参考。

Have a look at the end of the Timer's Documentation for reference to this scenario.

示例代码中的注释为:


        Normally, the timer is declared at the class level,
        so that it stays in scope as long as it is needed.
        If the timer is declared in a long-running method,  
        KeepAlive must be used to prevent the JIT compiler 
        from allowing aggressive garbage collection to occur 
        before the method ends. 

这篇关于System.Timers.Timer生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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