【发布时间】:2013-02-28 19:45:24
【问题描述】:
我有一个设置和显示文本框的表单。在表单加载方法中,我从一个完全独立的类名Processing开始一个新线程:
private void Form1_Load(object sender, EventArgs e)
{
Processing p = new Processing();
Thread processingThread = new Thread(p.run);
processingThread.Start();
}
这里是处理类。我想做的是在Utilities 类中创建一个方法,该方法允许我从我需要的任何类更新文本框:
public class Processing
{
public void run()
{
Utilities u = new Utilities();
for (int i = 0; i < 10; i++)
{
u.updateTextBox("i");
}
}
}
最后是Utilites 类:
class Utilities
{
public void updateTextBox(String text)
{
//Load up the form that is running to update the text box
//Example:
//Form1.textbox.appendTo("text"):
}
}
我已经阅读了Invoke 方法、SynchronizationContext、后台线程和其他所有内容,但几乎所有示例都使用与 Form 线程相同的类中的方法,而不是来自单独的类。
【问题讨论】:
-
使用单独的线程更改界面时要小心;你可能会遇到几个例外。他们通常建议界面更改不要离开它所在的当前线程。
-
什么UI技术,WPF,WinForms?在 WPF 中,
Dispatcher使这种操作非常简单...... -
您没有指定您使用的 .NET 框架的版本,但如果您使用的是 .NET 4.5,请考虑使用
async/await来保持您的 UI 响应式一个线程。
标签: c#