use*_*183 2 c# user-interface multithreading textbox appendtext
我的文本框出了问题.
我有一个表示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);
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试做一些Invoke的东西但是没能正确使用它.
GUI要么自己锁定,要么继续无所事事.
如果您不在UI线程上,则无法访问winforms UI.尝试:
console.Invoke((MethodInvoker)delegate {
console.AppendText("\r\n" + line);
console.SelectionStart = console.Text.Length;
console.ScrollToCaret();
});
Run Code Online (Sandbox Code Playgroud)
这将把它撞到UI线程上.
| 归档时间: |
|
| 查看次数: |
3243 次 |
| 最近记录: |