c# - InvokeRequired 和 BeginInvoke 等效项

标签 c# wpf richtextbox begininvoke invokerequired

我的 Windows 窗体中有此功能,现在我正在尝试将我的工作转移到 WPF, 传输后,我注意到 WPF 不支持 InvokeRequiredBeginInvoke。我正在寻找将我的函数转换为 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.CheckAccessDispatcher.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/

相关文章:

wpf - 如何按完整日期格式化 WPFToolkit.DataGridTextColumn?

wpf - 从 View 模型类调用 RichTextBox.ScrollToEnd()

没有设置宽度的 WPF RichTextBox

c# - 使用 WPF DrawingContext 时如何设置 Z 索引?

c# - 改进具有双重属性的数据结构

c# - Jenkins 未能建立C#项目

c# - 使用 MVCContrib 对 MVC 3 Controller 和 View 进行单元测试时,将键和值添加到 RouteData

c# - 使用 viewmodel 命令打开新选项卡

javascript - 可以即时进行语法突出显示的文本区域?

c# - DataTable 在 RejectChanges 上抛出异常