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();
}
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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With