Stop DispatcherTimer in its anonymous Tick event handler

Is it possible 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(); } 
+6
source share
3 answers

Matt raises the question of how you attach an anonymous method so that there is no easy way to separate it. Here is a generic template that you can use so you can disconnect if necessary.

 private void MyFunction() { DispatcherTimer timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 1); EventHandler eh = null; eh = (object sender, object e) => { timer.Tick -= eh; timer.Stop(); // Some code here }; timer.Tick += eh; timer.Start(); } 

However, in this particular case, there is nothing wrong with the way your source code works, as the timer becomes collectable as soon as it stops.

+5
source

Yes. Your timer fires once.

+4
source

Edit: I will rephrase my answer based on the comments. In the situation you gave, yes, it is completely safe to use an anonymous delegate.

There are several situations where adding an anonymous delegate and not disabling it can prevent your class from being garbage collected (for example, attaching an anonymous delegate to singleton). See this answer for information on when it is, and there is no need to detach the event handler.

+2
source

Source: https://habr.com/ru/post/899835/


All Articles