我正在开发一个与服务器通信的应用程序。
thread = new Thread(new ThreadStart(ClientStart));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
private void ClientStart()
{
tcpClient = new TcpClient(ip,3000);
stream = tcpClient.GetStream();
while (true) {
stream.Read(...);
PrintMessage(...);
.....
}
}
private void PrintMessage(LogWin w, string msg)
{
DateTime dt = DateTime.Now;
w.GetMessageBox().Dispatcher.BeginInvoke(DispatcherPriority.Input,new Action(()=>w.GetMessageBox()
.AppendText(String.Format("{0:d/M/yyyy HH:mm:ss}", dt) + " : " + msg)));
}
稍后我需要将结果打印到消息框。我知道我必须使用 Dispatcher,因为我在另一个线程中工作,但即使我使用 beginInvoke 方法我的应用程序也会卡住。
根据 Sheridan 的回答进行编辑:
现在我得到: WindowsBase.dll 中出现“System.InvalidOperationException”类型的未处理异常
附加信息:调用线程无法访问此对象,因为另一个线程拥有它。
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
thread = new Thread(() => ClientStart(dispatcher));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
private void ClientStart(Dispatcher dispatcher)
{
....
并更改了打印方法:
dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(() =>
w.GetMessageBox()
.AppendText(String.Format("{0:d/M/yyyy HH:mm:ss}", dt) + " : " + msg)));
已解决,使用 Application.Current.Dispatcher
最佳答案
始终警惕 Dispatcher.CurrentDispatcher
,因为它会返回一个对象用于在 CURRENT 线程上进行调度 - 这可能不是 UI。您需要(通常几乎总是需要)UI 线程调度程序。
您可以通过 Application.Current.Dispatcher
获取它,它始终返回 UI 线程调度程序。
令人沮丧的是这些电话看起来如此相似......
[如果您在主窗口中,您可以调用 Dispatcher
,但对您而言可能并非如此]
关于c# wpf dispatcher.beginInvoke 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23807045/