12

I use SetTimer API and I see a lot of code like this:

case WM_DESTROY: 
    // Destroy the timer. 
    KillTimer(hwnd, IDT_TIMER); 
    PostQuitMessage(0); 
    break; 

Do I have to call KillTimer or the system will automatically free resources on the process exit? Does forgetting to call KillTimer lead to resource leaks?

I understand that if the timer is not needed it CAN be destroyed by KillTimer. But MUST it be destroyed manually?

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Sergey Podobry
  • 7,101
  • 1
  • 41
  • 51
  • I've made some researches and found out: Wnen a window is being destroyed cleanup routines are invoked (DestroyWindowsTimers from xxxFreeWindow call). – Sergey Podobry Aug 03 '09 at 08:18

3 Answers3

13

Timers set from HWNDs are implicitly destroyed by the window (hwnd) being destroyed. So no, you don't have to clean up your timers when the window exits.

But it's a good practice to have all your resources related to the window cleaned up on window close.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
selbie
  • 100,020
  • 15
  • 103
  • 173
5

The timer will be destroyed automatically by Windows on process exit.

But bear in mind that (so it appears) your timer belongs to the window, not the process. So if your application allows these windows to be created and destroyed within a process, you'll be leaking timers.

It's always good practice to clean things up explicitly, because otherwise the lack of cleanup can come back to bite you later on.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • I don't believe that is correct to say timers will leak when the window is destroyed. Maybe in the old Windows 95/98 days, a timer could leak. But definitely on XP and up, timers set on hwnds are cleaned up when the window is destroyed. – selbie Jul 28 '09 at 08:16
  • 4
    @selbie: Yes, I'm sure you're right. But I still say it's good practice to assume that things will leak unless you clean them up explicitly. Imagine you change from window-based timers to callback-based ones - then you will have a leak unless you explicitly kill them. – RichieHindle Jul 28 '09 at 20:09
0

According to MSDN, one should kill timers:

Applications should use the KillTimer function to destroy timers that are no longer necessary. The following example destroys the timers identified by the constants IDT_TIMER1, IDT_TIMER2, and IDT_TIMER3.

// Destroy the timers.
KillTimer(hwnd, IDT_TIMER1);
KillTimer(hwnd, IDT_TIMER2);
KillTimer(hwnd, IDT_TIMER3);

https://msdn.microsoft.com/en-us/library/windows/desktop/ms644901(v=vs.85).aspx#creating_timer

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
10100111001
  • 735
  • 15
  • 31