我有一个winform和一些线程。当我试图从其中一个线程访问winform中的字段时,出现了以下错误:Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.
如何解决此问题?
致敬,Alexandru Badescu
发布于 2010-10-31 20:29:05
所有控件都有一个名为Invoke的方法,该方法将委托作为第一个参数和可选的参数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.
}
}享受编程吧!
发布于 2010-10-31 20:03:37
在线程代码中,在更改textBox1之前,请检查textBox1.InvokeRequired,如果是,请使用textBox1.Invoke(aDelegate)
发布于 2010-10-31 20:32:12
Vercas的建议运行良好,但如果您喜欢内联代码,您也可以尝试选择匿名委托
richTextBox1.Invoke(new MethodInvoker(
delegate() {
richTextBox1.BackColor = Color.Cyan;
));对他来说+1 :)
https://stackoverflow.com/questions/4062993
复制相似问题