gpt4 book ai didi

c# - InvokeRequired 和 BeginInvoke 等效

转载 作者:行者123 更新时间:2023-11-30 22:21:18 26 4
gpt4 key购买 nike

我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com