Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will this Timer be released from memory?

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!

like image 265
JoeCool Avatar asked Feb 24 '11 22:02

JoeCool


1 Answers

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.

like image 200
Hans Passant Avatar answered Oct 16 '22 17:10

Hans Passant