在WPF中,UI线程中的界面物体是不能被UI以外的线程修改的,如果你想在非UI线程中修改界面物体值的话,可以使用System.Windows.Threading.Dispatcher类中的Invoke方法
public void DoWork()
{
ThreadPool.QueueUserWorkItem((WaitCallback)delegate(object o)
{ //现在在非UI线程中
bool isConnected = false;
Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
WriteMessageToWin("cannot connect to server");
});
}
private TextBlock WriteMessageToWin(string message)
{
tbTextBlock.Text = message;
}
{
ThreadPool.QueueUserWorkItem((WaitCallback)delegate(object o)
{ //现在在非UI线程中
bool isConnected = false;
Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
WriteMessageToWin("cannot connect to server");
});
}
private TextBlock WriteMessageToWin(string message)
{
tbTextBlock.Text = message;
}