C#后台工作者,winform."跨线程操作无效:"

gri*_*eer 2 c# multithreading backgroundworker winforms

我正在尝试使用Windows窗体以最基本的方式运行后台工作程序,例如获取后台进程来更改标签中的文本..我在这里获得了基本的后台工作程序代码.. http://www.albahari .com/threading/part3.aspx继承 我的表单中的代码..试图使它按下按钮然后生成后台工作线程,更改标签中的文本

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;

       namespace WindowsFormsApplication4
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }


            BackgroundWorker _bw = new BackgroundWorker();

             void backgroundio()
            {
                _bw.DoWork += bw_DoWork;
                _bw.RunWorkerAsync("Message to worker");

            }

             void bw_DoWork(object sender, DoWorkEventArgs e)
            {
                // This is called on the worker thread
                label1.Text = (string)(e.Argument);        // writes "Message to worker"
                // Perform time-consuming task...
            }

             void button1_Click(object sender, EventArgs e)
             {
                 backgroundio();
             }

        }
    }
Run Code Online (Sandbox Code Playgroud)

对于label1.Text =(string)(e.Argument); 我收到这个错误.

跨线程操作无效:控制'label1'从其创建的线程以外的线程访问.

感谢任何帮助!! :)

实际上,虽然我在这里可以解释这一行吗?

 _bw.DoWork += bw_DoWork;
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我不明白+ =有什么意义.你怎么能添加这些东西?

Che*_*eso 9

Q1

你的bw_doWork方法是静态的.这意味着对于您的类的所有实例,只有这些方法中的一种.该方法无法访问特定于实例的属性或字段或方法.这解释了编译器错误.

如果您将该方法更改为非静态,则允许您在其中引用label1.


Q2.

您引用的语法是向该事件添加事件处理程序的快捷方式.

它只是意味着"将此处理程序添加到给定事件的处理程序列表中".这样做的长期方法是使用AddEventHandler.

http://msdn.microsoft.com/en-us/library/system.reflection.eventinfo.addeventhandler.aspx

Q3

您在运行时获得的神秘消息表明您无法更新非uI线程上的UI对象.(bg worker意味着不同的线程.)解决方案是在UI线程上执行所需的更新.

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    // This is called on the worker thread
    UpdateLabel((string)e.Argument));
      ...more work here...
}

void UpdateLabel(string s)
{
    if (this.label1.InvokeRequired)
    {
        // It's on a different thread, so use Invoke.
        this.BeginInvoke (new MethodInvoker(() => UpdateLabel(s));
    }
    else
    {
        // It's on the same thread, no need for Invoke
        this.label1.Text = s;
    }
}
Run Code Online (Sandbox Code Playgroud)

要了解有关它的更多信息,请访问http://msdn.microsoft.com/en-us/library/ms171728(v=vs.90).aspx