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!