Reputation: 10092
I've just seen this question, where one of the answers indicates that System.Diagnostics.Stopwatch should only be used for diagnosing performance and not in production code.
In that case, what would be the best way to get precision timing in .NET? I'm currently in the early stages of building a very simple MIDI sequencer using the MIDI-out functionality of NAudio. I'd like to be able to send MIDI messages out aligned to (say) 1/10s with as little jitter as possible. Is this feasible, or will things like context-switching ruin my day?
I currently have some code in a console app that continuously calls Stopwatch
and calculates the jitter when generating a stream of 1/16th-notes at 150bpm. The jitter is very low in this situation. However, I'll be moving this off to another thread, so I don't know if that will remain the case.
Upvotes: 10
Views: 3153
Reputation: 2128
I'm the author of DryWetMIDI. The library has playback functionality that works with help of WinMM high-precision timer. Timer is wrapped to MidiClock class so you can use it to drive your MIDI operations:
var midiClock = new MidiClock(true, new HighPrecisionTickGenerator(), TimeSpan.FromMilliseconds(1));
midiClock.Ticked += OnTick;
OnTick
will be called each 1 ms with this code.
Upvotes: 0
Reputation: 2027
Windows multimedia timer states that it allows "applications to schedule timer events with the greatest resolution (or accuracy) possible for the hardware platform."
The application it uses as an example is a MIDI sequencer.
Upvotes: 0
Reputation: 2463
You could also use the native streaming MIDI API. I don't think its in NAudio but you could look at the C# Midi Toolkit to see if that one supports it. Otherwise you have two examples of how to do native MIDI API P/Invoke and can roll your own...
Upvotes: 1
Reputation: 281525
If you don't mind P/Invoke, you can use QueryPerformanceCounter: http://www.eggheadcafe.com/articles/20021111.asp
Upvotes: 5