http://hi.baidu.com/wlmgnm/item/454d15256f173ee551fd87ee
主要原因是C#是主线程在运行,而WPF是代码和界面分开的两个线程在运行。
第一种方法:
WinForms
private
delegate
voidUpdateUiTextDelegate(Control control,
stringtext);
private voidUpdateUiText(Control control, stringtext)
{
if(InvokeRequired)
{
Invoke( newUpdateUiTextDelegate(UpdateUiText), new object[] {control, text});
return;
}
control.Text = text;
}
private voidUpdateUiText(Control control, stringtext)
{
if(InvokeRequired)
{
Invoke( newUpdateUiTextDelegate(UpdateUiText), new object[] {control, text});
return;
}
control.Text = text;
}
WPF
private
voidUpdateUiText(Control control,
stringtext)
{
if(!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(DispatcherPriority.Send, newUpdateUiTextDelegate(UpdateUiText), control, text);
return;
}
control.Text = text;
}
{
if(!Dispatcher.CheckAccess())
{
Dispatcher.Invoke(DispatcherPriority.Send, newUpdateUiTextDelegate(UpdateUiText), control, text);
return;
}
control.Text = text;
}
第二种方法:
C#:
private delegate void SetRichTextBoxReceiveCallBack(string str);
private SetRichTextBoxReceiveCallBack setRichTextBoxReceiveCallBack;
private SetRichTextBoxReceiveCallBack setRichTextBoxReceiveCallBack;
richTextBoxRecv.Invoke(setRichTextBoxReceiveCallBack, Encoding.UTF8.GetString(dataRead.msg, 0, recv));
使用委托进行的!
WPF:
private void showMessage(string msg)
{
Action action = () => richTextBoxRecv.AppendText(msg + "\r\n");
if (System.Threading.Thread.CurrentThread !=
richTextBoxRecv.Dispatcher.Thread)
{
richTextBoxRecv.Dispatcher.Invoke
(System.Windows.Threading.DispatcherPriority.Normal,
action);
}
else
{
action();
}
}
{
Action action = () => richTextBoxRecv.AppendText(msg + "\r\n");
if (System.Threading.Thread.CurrentThread !=
richTextBoxRecv.Dispatcher.Thread)
{
richTextBoxRecv.Dispatcher.Invoke
(System.Windows.Threading.DispatcherPriority.Normal,
action);
}
else
{
action();
}
}
showMessage(Encoding.UTF8.GetString(dataRead.msg, 0, recv).Trim());
也是使用委托,只是进行改造。