C#后台 worker ,winform。 "Cross-thread operation not valid:"

标签 c# winforms multithreading backgroundworker

我试图让后台 worker 以最基本的方式使用 Windows 窗体运行,例如获取后台进程来更改标签中的文本。我在这里获得了基本的后台 worker 代码。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();
             }

        }
    }

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

跨线程操作无效:从创建它的线程以外的线程访问控件“label1”。

感谢任何帮助!! :)

实际上,当我在这里时,有人可以解释一下这条线吗?

 _bw.DoWork += bw_DoWork;

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

最佳答案

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;
    }
}

要了解更多信息,http://msdn.microsoft.com/en-us/library/ms171728(v=vs.90).aspx

关于C#后台 worker ,winform。 "Cross-thread operation not valid:",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066725/

相关文章:

c# - 如何在 MVC 中为双因素身份验证电子邮件设置模板

c# - 验证显示 HDCP 合规性(强制 HDCP 输出,如果 HDCP 不可用则禁用输出)

c# - 使用 SMTP 在邮件正文中发送多个文本框值

c# - 如何从 DataGridView 中的行选择中获取最后选定行的索引

python - 多线程性能开销

c# - 侧边栏中带有标题列表的新闻页面

c# - HTML 到 PDF - 使用 HtmlRenderer 分页

c# - 如何在设计时禁用窗体调整大小?

c# - 为什么 TaskFactory.StartNew 方法不是通用的?

java - java 线程如何使 UI 响应更快?