在 C# 中,我应该在哪里保存我的计时器的引用? [英] In C#, where should I keep my timer's reference?

查看:35
本文介绍了在 C# 中,我应该在哪里保存我的计时器的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Threading.Timer 的文档说我应该为它保留一个实时引用以避免它被垃圾收集.但是我应该在哪里做呢?我的 main 很简单,我不知道在哪里保存引用:

The documentation of System.Threading.Timer says that I should keep a live reference for it to avoid it being garbage collected. But where should I do that? My main is very simple that I don't know where to keep the reference:

class Program {
    static void Main() {
        new System.Threading.Thread(myThreadStart).Start();
        new System.Threading.Timer(myTimerCallback, new MyStateObject(), 0, 5000);
    }
}

我考虑将引用保留在 Program 类中的 static 字段中,假设 static 字段直到最后才被收集的应用程序.但我不确定这是最好的方法,所以我很感激你的建议.

I thought about keeping the reference in a static field in the Program class, assuming that static fields do not get collected until the end of the application. But I'm not sure this is the best way to do it, so I'd appreciate your advice.

推荐答案

如果您的 Timer 是应用程序级对象,那么将其设为 Main 类的私有静态成员并没有错.无论如何,这就是我要做的.

If your Timer is an application-level object there's nothing wrong with making it a private static member of your Main class. That's what I would do, anyway.

这篇关于在 C# 中,我应该在哪里保存我的计时器的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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