我的 Windows 窗体中有此功能,现在我正在尝试将我的工作转移到 WPF,
传输后,我注意到 WPF 不支持 InvokeRequired
和 BeginInvoke
。我正在寻找将我的函数转换为 WPF 的正确方法:
delegate void DisplayInvoker(string text, MessageType type);
private void DisplayinRichbox(string text, MessageType type = MessageType.Normal)
{
if (this.InvokeRequired) // not support by WPF
{
this.BeginInvoke(new DisplayInvoker(DisplayinRichbox), text, type); // Not support by WPF
return;
}
txt_Log.AppendText(String.Format("[{0}] {1}{2}\r\n",
DateTime.Now, type == MessageType.Incoming ? "<< " : type == MessageType.Outgoing ? ">> " : "", text));
txt_Log.ScrollToCaret(); // not support by WPF
}
这是我的主类中的线程循环:
while (bWaiting == true)
{
//System.Windows.Forms.Application.DoEvents(); // i comment it because i cant find equivalent in WPF
System.Threading.Thread.Sleep(15);
}
最佳答案
WPF 中的等效项是 Dispatcher.CheckAccess和 Dispatcher.BeginInvoke :
if (!this.Dispatcher.CheckAccess())
{
this.Dispatcher.BeginInvoke(new Action(() => DisplayInRichbox(text, type)));
return;
}
编辑:
您的 RichTextBox
从未更新的原因是您阻塞了 UI 线程:
while (bWaiting == true)
{
//System.Windows.Forms.Application.DoEvents(); // i comment it because i cant find equivalent in WPF
System.Threading.Thread.Sleep(15);
}
这将阻止 UI 中的任何内容更新,因为您阻止了它并且从未提供让它正确更新的方法。在旧的 Win Forms 代码中,您调用了 DoEvents() 来处理消息(但由于多种原因,这是一个非常糟糕的主意)。如果没有这个调用,这将无法正常工作。
您应该尽量避免 UI 线程中的阻塞和循环 - 相反,在后台线程中完成工作,并让 UI 线程正常运行。 BackgroundWorker
使这变得更加简单,TPL 中的许多选项也是如此。
关于c# - InvokeRequired 和 BeginInvoke 等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14471074/