WPF DispatcherTimer some personal views

wpf in DispatcherTimer basic usage, this article does not describe. The main write something different, to remind myself not to make the same mistake.

A few days ago found that when writing code. When you create a non-UI thread DispatcherTimer instance, the program can not 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();
}

void DispatcherTimer_Click Private (SENDER Object, EventArgs E)
{
Console.WriteLine ( "DispatcherTimer_Click");
}
In DispatcherTimer_Click breakpoint function entry, the program found inaccessible.

​​

If such an object is created

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();
}

void DispatcherTimer_Click Private (SENDER Object, EventArgs E)
{
Console.WriteLine ( "DispatcherTimer_Click");
}
procedure Tick event can enter.

Or create such objects

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 following reasons

DispatcherTimer.Tick integrated into specified intervals and the specified priority queue Dispatcher process timer.

When you create DispatcherTimer objects in the thread, DispatcherTimer the Dispatcher is the thread Dispatcher.

If the thread at a time if there is no operation UI object, it Dispatcher == null, as detailed blog https://www.cnblogs.com/DoNetCoder/p/4369903.html

Guess you like

Origin www.cnblogs.com/njit-77/p/11468898.html