I'm writing a C# / WPF application that needs to run some code every 10 ms or so (I understand Windows is not real-time). Since I'm running on Windows 7, the system tick of ~15 ms limits me from using the built-in .NET timer types.
I implemented the Multimedia timer as detailed [here] by user mike-z (High resolution timer in C#), but seem to be running into the same issue hurcan solter was seeing. Unfortunately I'm not well versed in C# to follow his proposed solution:
create the callback delegate yourself and use GCHandle.Alloc()
I'm not very experienced with C# or managed code, but from what I can tell, the issue is related to this line:
timerId = NativeMethods.TimeSetEvent((uint)Interval, (uint)Resolution, TimerCallback, ref userCtx, 1);
Where the TimerCallback() function is being garbage collected -- is that right?
So it sounds like I need to create a reference to this callback in my main / managed function, and then pass that to the timer (maybe as an input argument to the Start()
function) ?
But I'm not sure where I would need to use GCHandle.Alloc()
, in this case.