The basic usage of Dispatcher Timer in wpf is not described in this article. Write something different to remind yourself not to make the same mistake again.

When I wrote the code the other day, I found out. When a Dispatcher Timer instance is created in a non-UI thread, the program cannot enter the Tick event

private static System.Windows.Threading.DispatcherTimer timer;

private void Button_Click(object sender, RoutedEventArgs e)
{
    new System.Threading.Thread(CreateTimer).Start();
}

private void CreateTimer()
{
    timer = new System.Windows.Threading.DispatcherTimer();
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += DispatcherTimer_Click;
    timer.Start();
}

private void DispatcherTimer_Click(object sender, EventArgs e)
{
    Console.WriteLine("DispatcherTimer_Click");
}

A breakpoint is set at the entry of the DispatcherTimer_Click function, and it is found that the program is unable to enter.

If you create objects like this

private static System.Windows.Threading.DispatcherTimer timer;

private void Button_Click(object sender, RoutedEventArgs e)
{
    new System.Threading.Thread(CreateTimer).Start();
}

private void CreateTimer()
{
    timer = new System.Windows.Threading.DispatcherTimer(System.Windows.Threading.DispatcherPriority.SystemIdle, this.Dispatcher);
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += DispatcherTimer_Click;
    timer.Start();
}

private void DispatcherTimer_Click(object sender, EventArgs e)
{
    Console.WriteLine("DispatcherTimer_Click");
}

Programs can enter Tick events.

Or create objects like this

private static System.Windows.Threading.DispatcherTimer timer;

private void Button_Click(object sender, RoutedEventArgs e)
{
    new System.Threading.Thread(CreateTimer).Start();
}

private void CreateTimer()
{
    this.Dispatcher.Invoke(() => 
    {
        timer = new System.Windows.Threading.DispatcherTimer();
    });
    timer.Interval = TimeSpan.FromSeconds(1);
    timer.Tick += DispatcherTimer_Click;
    timer.Start();
}

private void DispatcherTimer_Click(object sender, EventArgs e)
{
    Console.WriteLine("DispatcherTimer_Click");
}

The reasons are as follows

Dispatcher Timer. Tick integrates timers into Dispatcher queues processed at specified intervals and priorities.

When creating Dispatcher Timer objects in a thread, Dispatcher Timer's Dispatcher is the thread's Dispatcher.

At this point, if a thread does not operate on UI objects, its Dispatcher==null. See blog for details.