In WPF applications, if you encounter a multi-threaded demand, will lead to reference WPF control if abnormal, abnormal contents: The calling thread can not access this object because another thread owns the object. details as follows:
Calling code:
new Thread(new ThreadStart(Count));
countThread.Start();
In the Count method called throws an exception as follows
WPF objects are derived from DispatcherObject, which provides the basic structure for handling concurrency and threads. WPF based messaging system scheduler implementation. It works with popular Win32 message pump is very similar; in fact, WPF Scheduler uses User32 message to perform cross-thread calls. When updating UI WPF user thread, to be conducted through Dispatcher.
Called See the following code:
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
Thread countThread;
public MainWindow()
{
InitializeComponent();
this.textBox1.Text = DateTime.Now.ToLocalTime().ToString("yyyy年MM月dd日 hh:mm:ss"); ;
countThread = new Thread(new ThreadStart(DispatcherThread));
}
private void button3_Click(object sender, RoutedEventArgs e)
{
if (button3.Content.ToString() == "开始时间线程")
{
button3.Content = "thread stop time";
IF (countThread.ThreadState == ThreadState.Suspended)
{
// thread continues
countThread.Resume ();
}
the else
countThread.Start ();
}
the else
{
button3.Content = "Start Time thread ";
// thread suspension
countThread.Suspend ();
}
}
public void DispatcherThread ()
{
// update the UI may be controlled by cycling conditions
the while (to true)
{
/// thread priority, maximum timeout, the method delegate (no reference method)
textBox1.Dispatcher.Invoke (
DispatcherPriority.Normal, TimeSpan.FromSeconds (. 1), the Action new new (UpdateTime));
the Thread. SLEEP (1000);
}
}
Private void UpdateTime ()
{
this.textBox1.Text = DateTime.Now.ToLocalTime () the ToString. ( "date YYYY, mM-dd HH: mm: SS");
}
Private void WINDOW_CLOSED (Object SENDER, EventArgs E)
{
countThread.Abort ();
Application.Current.Shutdown ();
}
}
}
Run effect is shown