0

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!

  • This is not a problem, but your topic is closed and I cannot give an answer in it. You should have been more accurate in naming the theme, indicating that you get an exception when accessing the UI element from timer. Ask to open a topic and correct its name. Or create a new one topic . – EldHasp Apr 20 '21 at 20:34
  • The original duplicate was indeed inappropriate. However, this certainly is a duplicate question, and you certainly should not have posted a new copy of the question. If you need to access UI objects from any non-UI thread, you need to marshal that access properly. WPF provides a number of mechanisms to accomplish that, regular data binding being the preferred and simplest. See the updated duplicate target above. – Peter Duniho Apr 20 '21 at 20:46
  • You're making too many mistakes; you need to [find a simpler problem](https://ericlippert.com/2014/03/21/find-a-simpler-problem/). Use a background timer or async thread with no UI at all that monitors your sensor data. Get that working first before you try to do anything with a UI. – Dour High Arch Apr 22 '21 at 01:52

0 Answers0