简体   繁体   English

为什么即使分配了null后,Timer仍会触发Elapsed事件

[英]Why Timer still fire Elapsed event even after assigning null to it

I have a Timer set in my App.cs as follows : 我在App.cs中设置了一个Timer ,如下所示:

public static void SetSnipDeletingTimer(double d)
{
     TimeBeforeDeletingSpan = new Timer(d) {AutoReset = true, Enabled = true};
     TimeBeforeDeletingSpan.Elapsed += TimeBeforeDeletingSpan_Elapsed;
     TimeBeforeDeletingSpan.Start();
}

static void TimeBeforeDeletingSpan_Elapsed(object sender, ElapsedEventArgs e)
{
     foreach (var t in ListOfCapturesUriPaths) File.Delete(t);
}

In another class and in a certain logic I assign null to it to stop it, I just do this : 在另一个类中,以某种逻辑,我为它分配null以停止它,我只是这样做:

App.TimeBeforeDeletingSpan = null;

The problem is that the Elapsed event still get fired everytime the span passes, as shows this screenshot, where the break point is stoping inside the event though the object is null: 问题是,每次跨度过去时,Elapsed事件仍会触发,如此屏幕截图所示,尽管对象为null,但断点在事件内部停止:

在此处输入图片说明

How that can be possible ? 那怎么可能呢? and what should I do to stop the execution of that event ? 我应该怎么做才能停止执行该事件?

To prevent events that haven't been started yet: 为了防止尚未开始的事件:

 App.TimeBeforeDeletingSpan.Enabled = false;

To put the object in the dormant state (whatever that means to the object), 要将对象置于休眠状态(无论对对象意味着什么),

App.TimeBeforeDeletingSpan.Dispose();

The reason that assigning null to a field that previously referenced the object doesn't do anything with the object is that the object could be referenced by any other field or variable. 向先前引用该对象的字段分配null不会对该对象执行任何操作的原因是,该对象可以由任何其他字段或变量引用。 Only the garbage collector can find out and only when it runs. 只有垃圾收集器可以运行,才可以发现垃圾收集器。

Setting a null reference to an object does not dispose of the given object, if a type implements IDisposable, you'll need to dispose of it manually. 设置对对象的空引用不会处理给定的对象,如果类型实现IDisposable,则需要手动进行处理。

Another thing to keep in mind here is that Timers run on a separate thread, setting it to null won't prevent that thread from continuing to run, as mentioned earlier, you need to ensure that it's being disposed. 这里要记住的另一件事是,Timer在单独的线程上运行,将其设置为null不会阻止该线程继续运行,如前所述,您需要确保将其处置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM