I am trying to get a high-resolution timer to work with my tick in a WPF. My application performs some calculations based on sensor data in real time, and I am logging the data (5 Hz - every 200ms) into a CSV file with StreamWriter.
I am currently trying System.Timers.Timer to see if it works but I get this exception: "The calling thread cannot access this object because a different thread owns it"
I previously also tried System.Windows.Threading.DispatcherTimer but realized that it's not suitable as the drifts when calling the tick varies too much and I was getting inconsistent entries.
I've been searching for solutions and saw something about using Dispatcher.BeginInvoke for my tick, but it's a little confusing for me as I am new to C#.
Right now my implementation is as follows:
Initializing Timer:
void TimerInit()
{
//recFreq = 5 Hz - Interval = 200 ms
timer.Interval = ((1 / recFreq) * 1000);
timer.Elapsed += new ElapsedEventHandler(Timer_Tick);
timer.AutoReset = true;
timer.Enabled = false;
}
Releasing Timer:
void TimerInit()
{
timer.Dispose();
}
Start Logging Button:
void OnClickStart(object sender, RoutedEventArgs e)
{
TimerInit();
timer.Enabled = true;
while (button_Stop.IsEnabled != true)
{
calculate();
}
}
Tick:
void Timer_Tick(object sender, ElapsedEventArgs e)
{
try
{
StreamWriter sw = new StreamWriter(*path*, true);
//Write Data
sw.Close();
}
catch (Exception ex)
{
//Print Error
TimerRelease();
}
}
Any ideas on how can I get this to work or implement it a better way?
Thank you very much, I appreciate any input!