BackgroundWorker-跨线程操作无效 [英] BackgroundWorker - Cross-thread operation not valid

查看:121
本文介绍了BackgroundWorker-跨线程操作无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个winform应用程序(一种形式),在这种形式上有一个RichTextBox。在这种形式的构造函数中,我创建了 MyClass 类的实例。在 Form_Load中,我从 MyClass 实例调用方法 Initialisation

I have a winform application (one form), on this form there is a RichTextBox. In the constructor of this form I create an instance of the class MyClass. In the "Form_Load" I call the method Initialisation from MyClass instance.

在表单构造器中

myClass = new MyClass(RichTextBox richTextBox);

在Form_Load中

myClass.Initialisation();

Initialisation 方法中,循环执行,我读了一些参数表来做其他的事情。为了不冻结应用程序(因为某些操作可能要花一些时间,几秒钟),我使用了 BackgroundWorker 。我这样使用它(请参见下面的代码)。

In the Initialisation method, in a loop, I read some parmeters do other stuffs. To not freeze the application (because some operation can take a while, some seconds), I use a BackgroundWorker. I use it like this (see code below).

执行时,出现此错误:跨线程操作无效:控制'richTextBox'
从该线程以外的其他线程访问它是在
上创建的。

When I execute, I get this error : Cross-thread operation not valid: Control ‘richTextBox’ accessed from a thread other than the thread it was created on.

您能告诉我如何解决吗?当我不访问 richTextBox

Could you tell me how solve this ? Work perfect when I don't access the richTextBox

public Class MyClass
{
    static BackgroundWorker _bw;
    public MyClass()
    {
        _bw = new BackgroundWorker
        {
            WorkerReportsProgress = true,
            WorkerSupportsCancellation = true
        };
        _bw.DoWork += bw_DoWork;
        _bw.ProgressChanged += bw_ProgressChanged;
        _bw.RunWorkerCompleted += bw_RunWorkerCompleted;
    }
    static void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        foreach (....)
        {
            if (....)
            {
                richtextBox.Text.AppendText("MyText");
            }
        }
        e.Result = true;
    }
    static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){}
    static void bw_ProgressChanged(object sender, ProgressChangedEventArgs e){}
}


推荐答案

使用 BackgroundWorker 不适用您具有正常的线程规则-例如UI线程只能访问

Using BackgroundWorker doesn't exempt you of the normal threading rules - such as that only the UI thread can access UI components.

如果要从 BackgroundWorker 除了使用进度/完成事件(在UI线程上引发)以外,您需要使用 Control.Invoke / Control.BeginInvoke ,就像您在其他情况下一样。例如:

If you want to update the UI from a BackgroundWorker other than using the progress/completion events (which are raised on the UI thread) you need to use Control.Invoke / Control.BeginInvoke just as you would in other situations. For example:

if (....)
{
    Action action = () => richtextBox.Text.Add("MyText");
    richtextBox.Invoke(action); // Or use BeginInvoke
}

这篇关于BackgroundWorker-跨线程操作无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆