0

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.

Lone Shepherd
  • 965
  • 1
  • 7
  • 25
  • 1
    See the answers in [this related question](http://stackoverflow.com/questions/6193711/call-has-been-made-on-garbage-collected-delegate-in-c). You need to keep a reference to the delegate passed into that method. You shouldn't need `GC.Alloc` – Charles Mager Jul 20 '16 at 15:41
  • Thank you. Tim's answer was what I needed. I had looked at that question before, but apparently not closely enough. – Lone Shepherd Jul 20 '16 at 15:58

0 Answers0