I have a server that receives batches of signal samples from clients. Each batch can contain up to 1000 samples and be received once per second (1000 Hz). Once I have received the samples, I want to publish them locally via an Observable at the same frequency they were generated from the signal source device. I have put together the following concept code that accomplishes what I want to do.
LINQPad code:
var frequency = 1000; // samples / second
int sampleCount = 1000;
var samples = Enumerable.Range(1, sampleCount).ToArray();
ManualResetEvent done = new ManualResetEvent(false);
int count = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
samples.ToObservable()
.Do(_ => Thread.Sleep(1000/frequency))
.Subscribe((next) => count++, () => { sw.Stop(); done.Set(); });
done.WaitOne();
sw.ElapsedMilliseconds.Dump("Subscription duration");
count.Dump("Items observed");
I tried other ways to simulate the delay between samples, but at such high frequencies, any timer-based or task-based approaches apparently had too much overhead to keep up. So my question(s) are:
- Is this the best approach to delaying a high frequency observable?
- In the Do(...) method, it is the 'SubscribeOn' thread that I am putting to sleep, right?
- Should I explicitly be calling the SubscribeOn() and ObserveOn() method to help ensure that the observer code does not interfere with publishing of the samples?
Thanks in advance!