我有一个winform和一些线程。当我尝试从其中一个线程访问winform中的字段时,会发生以下错误:
Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
我该如何解决这个问题?
此致 Alexandru Badescu
答案 0 :(得分:4)
所有控件都有一个名为Invoke的方法,该方法将一个委托作为第一个参数,并选择 params object [] 。
您可以轻松使用此方法:
richTextBox1.Invoke(new MethodInvoker(DoSomething));
其中
void DoSomething()
{
richTextBox1.BackColor = Color.Cyan;
}
委托MethodInvoker位于System.Windows.Forms命名空间中,我想,您已经在使用它了。
你甚至可以从同一个线程调用!
您还可以使用参数,如下所示:
richTextBox1.Invoke(new ColorChanger(DoSomething), Color.Cyan);
其中
delegate void ColorChanger(Color c);
void DoSomething(Color c)
{
richTextBox1.BackColor = c;
}
我希望这有帮助!
编辑:
如果你使用的是......基本上......未知的线程,则需要InvokeRequired
。
所以它看起来像这样:
void DoSomething()
{
if (richTextBox1.InvokeRequired)
richTextBox1.Invoke(new MethodInvoker(DoSomething));
else
{
richTextBox1.BackColor = Color.Cyan;
// Here should go everything the method will do.
}
}
您可以从任何线程调用此方法!
参数:
delegate void ColorChanger(Color c);
void DoSomething(Color c)
{
if (richTextBox1.InvokeRequired)
richTextBox1.Invoke(new ColorChanger(DoSomething), c);
else
{
richTextBox1.BackColor = c;
// Here should go everything the method will do.
}
}
享受编程!
答案 1 :(得分:2)
在线程代码中,在更改textBox1之前,请选中textBox1.InvokeRequired
,如果是,请使用textBox1.Invoke(aDelegate)
答案 2 :(得分:2)
Vercas建议的工作正常,但如果你喜欢内联代码,你也可以尝试选择匿名代表
richTextBox1.Invoke(new MethodInvoker(
delegate() {
richTextBox1.BackColor = Color.Cyan;
));
+1给他:)
答案 3 :(得分:1)
Salut Alexandru
您可能想查看另一种方法,
BackgroundWorker的
组件。它使用起来非常简单和舒适。您可以在此处找到更多详细信息和样本
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
这个组件在.NET中也非常重要,非常有用。