在其自己的匿名 Tick 事件处理程序中停止 DispatcherTimer
做这样的事情是否安全:
private void MyFunction()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += (object sender, object e) =>
{
timer.Stop();
// Some code here
};
timer.Start();
}
Is it safe to do something like this:
private void MyFunction()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += (object sender, object e) =>
{
timer.Stop();
// Some code here
};
timer.Start();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
马特提出了这样的观点:附加匿名方法的方式没有简单的方法可以将其分离。您可以使用以下通用模式来在必要时进行分离。
然而,在这种特定情况下,原始代码的工作方式没有任何问题,因为计时器一旦停止就可以收集。
Matt raise the point that the way you attach the anonymous method that there is no easy way to detach it. Here is a general pattern you can use to enable you to detach if necessary.
However in this specific case there is nothing wrong with the way your original code works since the timer becomes collectable as soon as it is stopped.
是的。您的计时器将触发一次。
Yes. Your timer will fire once.
编辑:我将根据评论重新表述我的答案。在您给出的情况下,是的,使用匿名委托是完全安全的。
在某些情况下,添加匿名委托而不分离它可能会阻止您的类被垃圾收集(例如,将匿名委托附加到单例)。有关何时发生的信息,请参阅此答案不需要也不需要分离事件处理程序。
Edit: I'll rephrase my answer based on the comments. In the situation you've given, yes it's perfectly safe to use an anonymous delegate.
There are some situations in which adding an anonymous delegate and not detaching it could prevent your class from being garbage collected (for example, attaching an anonymous delegate to a singleton). See this answer for information about when it is and isn't necessary to detach the event handler.