Question

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();
}
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top