Porting SetTimer() and KillTimer() to C#?
I am trying to port some code from C++ to C#.
I came across this i开发者_如何学Cn the C++ code:
watchdogTimer = SetTimer(1,1000,NULL);
...
KillTimer(watchdogTimer);
What is this code doing, and how can this be ported to C#?
Thanks.
The CWnd::SetTimer
function you're looking at creates a timer that sends WM_TIMER
events to the window. This is analogous to the System.Windows.Forms.Timer component in .NET. It behaves somewhat differently than the System.Timers.Timer
. There are two differences that are particularly relevant:
Windows.Forms.Timer
calls the event handler on the UI thread. By default, System.Timers.Timer
calls the event handler on a threadpool thread. You can use SynchronizingObject property to have the System.Timers.Timer
call on the UI thread.
Another difference is that it's not possible to encounter reentrancy problems with the Windows Forms timer because Windows won't allow multiple WM_TIMER
messages from the same timer in the queue, nor will it place a WM_TIMER
message in the queue if one is already being processed. This is generally a good thing.
System.Timers.Timer
, on the other hand, will allow reentrancy. So if your timer event handler takes longer than the timer period, you can be processing multiple events for the same timer concurrently. If your timer period is 100 ms and processing takes 150 ms, you're going to get another notification while you're processing the first one. If you use the SynchronizingObject
to force the callback on the UI thread, this can lead to a whole bunch of pending callbacks being queued.
The implementation of the two timers is quite different. The Windows Forms timer uses old style Windows timers that have been around for 20 years. This type of timer requires a window handle and a message loop, and is therefore used only in GUI programs. System.Timers.Timer
is a thin wrapper around System.Threading.Timer
, which uses the Windows Thread Pool Timers.
Assuming that your application is written under MFC, the SetTimer() method belongs to class CWnd and is responsible for setting up a windows timer. Documentation for this can be found at http://msdn.microsoft.com/en-us/library/49313fdf(v=vs.80).aspx. I know little about .NET but a quick google search located the following this: http://msdn.microsoft.com/en-us/library/0tcs6ww8(v=VS.90).aspx.
精彩评论