System.Threading.Timer为空会使它停止吗? [英] does nulling a System.Threading.Timer stop it?

查看:49
本文介绍了System.Threading.Timer为空会使它停止吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个活动的系统.Threading.Timer ,我将其设置为null,它停止了吗?

If I have an active System.Threading.Timer and I set it to null, is it stopped?

我意识到,调用 .Dispose()更合适,但我希望得到书面答复.

I realize that it is more proper to call .Dispose() but I would like an answer to the question as written.

public class Foo
{
   private System.Threading.Timer _timer;
   public Foo()
   {
      // initialize timer
   }

   public void KillTimer()
   {
      _timer=null;
   }
}


更新:

在反复讨论是否将对System.Threading.Timer的单个引用设置为null确实会导致停止该操作


Update:

After much back and forth about whether setting a single reference to a System.Threading.Timer to null will indeed result stopping it have shown that

  1. 没有缠绵的参考文献,例如事件列表,因为线程计时器接受单次回调并且不公开事件.
  2. 如果 GC收集到的
  3. ,终结器确实将处置TimerBase并停止计时器.

using System;
using System.Threading;

namespace SO_3597276
{
    class Program
    {
        private static System.Threading.Timer _timer;

        static void Main(string[] args)
        {
            _timer = new Timer((s) => Console.WriteLine("fired"), null, 1000, Timeout.Infinite);
            _timer = null;
            GC.Collect();
            Console.ReadKey();
        }
    }
}

不调用计时器回调.删除 GC.Collect()并调用回调.

The timer callback is not called. Remove GC.Collect() and the callback is called.

谢谢.

推荐答案

不一定.将其设置为null,删除对它的所有引用,并依靠垃圾收集器对其进行处理.

Not necessarily. Setting it to null, removes any references to it, and relies on the garbage collector to dispose of it.

如果计时器在GC到达之前关闭,它将触发事件.

If the timer went off before the GC got to it, it would trigger the event.

这篇关于System.Threading.Timer为空会使它停止吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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