gpt4 book ai didi

C# AppendText 从另一个线程不工作的 TextBox

转载 作者:行者123 更新时间:2023-11-30 19:44:55 24 4
gpt4 key购买 nike

我的文本框有问题。
我有一个代表 GUI 线程的类和一个用于执行一些网络工作的工作线程的类,然后必须将日志添加到 GUI 线程中的文本框,以便您可以看到后台发生的事情。
但是,我遇到的问题是 GUI 上没有任何反应,控制台中只有调用 addLine() 的调试信息。
应该添加日志的方法 addLine() 被调用,但似乎 AppendText() 什么也没做。
我很确定这与线程有关,但我不确定如何解决这个问题。

代码如下:

工作线程:

    Form1 form = new Form1();
// This method gets called in the worker thread when a new log is available
private void HandleMessage(Log args)
{
// Using an instance of my form and calling the function addLine()
form.addLine(args.Message);
}

GUI线程:

    // This method gets called from the worker thread
public void addLine(String line)
{
// Outputting debug information to the console to see if the function gets called, it does get called
Console.WriteLine("addLine called: " + line);
// Trying to append text to the textbox, console is the textbox variable
// This pretty much does nothing from the worker thread
// Accessing it from the GUI thread works just fine
console.AppendText("\r\n" + line);

// Scrolling to the end
console.SelectionStart = console.Text.Length;
console.ScrollToCaret();
}

我已经尝试做一些 Invoke 的事情,但未能正确使用它。
GUI 要么自行锁定,要么继续不执行任何操作。

最佳答案

如果您不在 UI 线程上,则无法访问 winforms UI。尝试:

console.Invoke((MethodInvoker)delegate {
console.AppendText("\r\n" + line);

console.SelectionStart = console.Text.Length;
console.ScrollToCaret();
});

这会将它撞到 UI 线程上。

关于C# AppendText 从另一个线程不工作的 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11603227/

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