I am on Windows 10, Unity Editor 2018.3.12f1
I have a requirement for very fast (500 Hz) and precise updates, “independent” from the Unity main thread. I am targeting windows desktop only, so the Multimedia Timers seemed as a good (the only?) fit. However I witness some weird crashes.
When in Editor, when I press the play button, my sample game seems to be working correctly (ie prints in the Debug console, and with great precision when I used stopwatch to measure), but when i stop the game and try to run it again, the Editor hangs.
When i build and play, again everything seems normal (no debug messages there of course), but when i attempt to close the program via the ‘X’ button it hangs again.
I tried this library which also includes a working example, and I also created this very simple mono behaviour to test it but with same results:
using UnityEngine;
using System.Threading;
using System.Runtime.InteropServices;
using System;
public class MultimediaTimer : MonoBehaviour
{
private UInt32 userCtx = 0;
void Start()
{
// Run();
Thread r = new Thread(() => Run());
r.Start();
}
void Run()
{
MultimediaTimerCallback Callback = new MultimediaTimerCallback(TimerCallbackMethod);
uint timerId = TimeSetEvent(100, 5, Callback, ref userCtx, 1);
Thread.Sleep(1000);
TimeKillEvent(timerId);
}
private static void TimerCallbackMethod(uint id, uint msg, ref uint userCtx, uint rsv1, uint rsv2)
{
Debug.Log("Hi");
}
private delegate void MultimediaTimerCallback(UInt32 id, UInt32 msg, ref UInt32 userCtx, UInt32 rsv1, UInt32 rsv2);
[DllImport("winmm.dll", EntryPoint = "timeSetEvent")]
private static extern UInt32 TimeSetEvent(UInt32 msDelay, UInt32 msResolution, MultimediaTimerCallback callback, ref UInt32 userCtx, UInt32 eventType);
[DllImport("winmm.dll", EntryPoint = "timeKillEvent")]
private static extern UInt32 TimeKillEvent(UInt32 uTimerId);
}
My question is very simple. Is it possible to reliably call the multimedia timer from a Unity program? And if not could someone explain this behaviour I observe? I could encapsulate my timer logic in a separate process and use some form of IPC to achieve my requirement, but I would prefer for convenience to stay withing Unity.
(Of course if you know any alternatives, by all means do say them)