我有一个名为' Home'还有一个名为' Server'的类,它是有线程的。 Home有一个TextBox,我希望在服务器中发生事情时附加。什么是最简单的线程安全方式来附加不在同一个类中的文本框?我看到很多关于这个问题的讨论,但似乎没有回答我的问题。其他解决方案也包含很多代码,看似简单。
我是这样开始我的主题形式的主页:
public void StartThread()
{
Server s = new Server();
Thread t = new Thread(s.DoWork);
t.Start();
}
class Server
{
public void DoWork()
{
while (!_shouldStop)
{
StartServer();
}
}
public void RequestStop()
{
_shouldStop = true;
}
private volatile bool _shouldStop;
internal void StartServer()
{
try
{
// Server Stuff
// Something happens here and I want to append a string to the text box in Home.
}
catch (Exception)
{
//Exception, append text box with some other string.
}
}
答案 0 :(得分:2)
Progress<string>
instace,IProgress<string>
实例。 Progress
类将处理将代码封送到UI线程。
这确保了UI与非UI代码的正确分离。
答案 1 :(得分:0)
我不确定这是不是你的意思(我假设执行交叉线程操作?)但是......
textBox1.Invoke(new MethodInvoker(delegate { textBox1.AppendText("Hi"); }));
这可以安全地将一些文本附加到文本框中,您只需要添加if语句等。