Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping DispatcherTimer in its own anonymous Tick event handler

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();
}
like image 545
K Mehta Avatar asked Oct 21 '11 23:10

K Mehta


3 Answers

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.

like image 130
AnthonyWJones Avatar answered Nov 14 '22 04:11

AnthonyWJones


Yes. Your timer will fire once.

like image 4
driis Avatar answered Nov 14 '22 06:11

driis


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.

like image 2
Matt Bridges Avatar answered Nov 14 '22 05:11

Matt Bridges