繁体   English   中英

在另一个线程上访问数据

[英]Accessing data on another thread

我有一个winform和一些线程。 当我尝试从其中一个线程访问winform中的字段时,会发生以下错误: Cross-thread operation not valid: Control 'richTextBox1' accessed from a thread other than the thread it was created on.

我该如何解决这个问题?

问候,亚历山德鲁·巴德斯库

所有控件都有一个称为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.
    }
}

享受编程!

在您的线程代码中,更改textBox1之前,请检查textBox1.InvokeRequired ;如果这样,请使用textBox1.Invoke(aDelegate)

Vercas提出的建议效果很好,但是如果您喜欢内联代码,也可以尝试选择一个匿名委托

richTextBox1.Invoke(new MethodInvoker(
    delegate() {
        richTextBox1.BackColor = Color.Cyan;
    ));

+1 :)

Salut Alexandru

您可能想看看另一种方法,

后台工作者

零件。 它真的很容易使用。 您可以在此处找到更多详细信息和样本

http://msdn.microsoft.com/zh-CN/library/system.componentmodel.backgroundworker.aspx

该组件在.NET中也是非常重要的组件,并且非常有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM