Will this Timer be released from memory?

1.6k views Asked by At

Consider this pair of functions in C#:

void func1() {
    DispatcherTimer tmr = new DispatcherTimer();
    tmr.Interval = TimeSpan.FromSeconds(5);
    tmr.Tick += func2;
    tmr.Start();
}

void func2(object a, EventArgs b) {
    // Called every 5 seconds once func1() is called
}

After calling func1() once, func2() is called every 5 seconds from then on, even though I lose the reference to my timer since its scope is restricted to func1(). That means that the timer is obviously still in memory, doing its thing, long after func1() was called. My question is, if I add this to func2():

void func2(object a, EventArgs b) {
    // Called every 5 seconds once func1() is called

    ((DispatcherTimer)a).Stop()
}

will the timer be picked up by garbage collection soon after, or will it continue to stay in memory until the program exits? If it stays in memory, how can I mark it for collection manually (or do something similar)?

A secondary question I have (if you feel inclined to answer) is if a regular Timer would have the exact same behavior in this situation or if there is a significant difference I should know about.

Thanks!

3

There are 3 answers

0
Hans Passant On BEST ANSWER

The Threading.Dispatcher class keeps a list of all active DispatcherTimers. When you call Stop() in the Tick event handler then the timer will be removed from that list. There are now no longer any references to the timer. It will eventually be garbage collected. Which is okay because there is no way to get the timer started again. After all, you don't have any way to get the reference anymore, the Tick event handler was your last shot at it.

0
nullforce On

According to this, you'll have to call stop and remove the handler.

0
Mani On

Basically a DispatcherTimer spawns a new Thread.So its scope cannot be defined as normally we would think. You could alternatively kill the thread by specific methods.