Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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

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.

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