none
Running reoccurring code on a separate thread RRS feed

  • Question

  • Hello! I have an object that uses a DispatcherTimer to execute some code every 300 milliseconds. I'm not incredibly familiar with DispatcherTimers but is the Tick event code run on a separate thread?

    For example...

                MyTimer = new DispatcherTimer();
                MyTimer.Tick += MyTimer_Tick;
                MyTimer.Interval = TimeSpan.FromMilliseconds(300);
                MyTimer.Start();        
    
    
                private void MyTimer_Tick(object sender, EventArgs e)
                {
                    // Code to execute
                }

    If not, what's the best way to make that happen?

    Thanks!

    Wednesday, June 5, 2019 2:52 PM

Answers

  • If this is an WPF application, then, according to documentation and samples, DispatcherTimer is not executed in separate threads. Consider another timer — System.Timers.Timer (https://docs.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatchertimer).

    In modern language you can also use “async”. Try a button that has this Click handler:

    private async void Button1_Click( object sender, RoutedEventArgs e )

    {

        for(; ; )

        {

            await Task.Delay( 300 ).ConfigureAwait( false );

     

     

            //.....

     

        }

    }

     

    The commented part is executed periodically in different threads. In order to access controls, you have to use functions like Dispatcher.Invoke.

    • Marked as answer by T Gregory Wednesday, June 5, 2019 5:08 PM
    Wednesday, June 5, 2019 4:15 PM

All replies

  • If this is an WPF application, then, according to documentation and samples, DispatcherTimer is not executed in separate threads. Consider another timer — System.Timers.Timer (https://docs.microsoft.com/en-us/dotnet/api/system.windows.threading.dispatchertimer).

    In modern language you can also use “async”. Try a button that has this Click handler:

    private async void Button1_Click( object sender, RoutedEventArgs e )

    {

        for(; ; )

        {

            await Task.Delay( 300 ).ConfigureAwait( false );

     

     

            //.....

     

        }

    }

     

    The commented part is executed periodically in different threads. In order to access controls, you have to use functions like Dispatcher.Invoke.

    • Marked as answer by T Gregory Wednesday, June 5, 2019 5:08 PM
    Wednesday, June 5, 2019 4:15 PM
  • Thanks! The System.Timers.Timer is what I was looking for.
    Wednesday, June 5, 2019 5:08 PM