后台工作者错误 [英] background worker error

查看:84
本文介绍了后台工作者错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我指定的代码错误?
我是用backgroundworker编写的.

Error in the code that I specify what?
I wrote this program with backgroundworker.

namespace WindowsFormsApplication21
{
    public partial class Form1 : Form
    {
        BackgroundWorker Worker=new BackgroundWorker();

        public Form1()
        {
            InitializeComponent();
            InitializeBackGroundWorker();
        }

        private void InitializeBackGroundWorker()
        {
          //  Worker = new BackgroundWorker();
            Worker.DoWork += new System.ComponentModel.DoWorkEventHandler(Worker_DoWork);
            Worker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(Worker_ProgressChanged);
            Worker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
            Worker.WorkerReportsProgress = true;
            Worker.WorkerSupportsCancellation = true;
        }


        void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
                label1.Text = e.Error.Message;

            else if(e.Cancelled)
                label1.Text="BackGroundWorker Canceled";

            label1.Text = "BackGroundWorker Complete.";
          
        }

        void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        void Worker_DoWork(object sender, DoWorkEventArgs e)
        {

            Worker = new BackgroundWorker();  

           BackgroundWorker worker=sender as BackgroundWorker;
           if (worker.CancellationPending)
           {
               e.Cancel = true;
               return;
           }


           label1.Text = "BackGroundWorker Started.";//Error Cross-thread operation not valid: Control ''label1'' accessed from a thread other than the thread it was created on.
            System.Threading.Thread.Sleep(1000000);
            Timer timer =new Timer();
            timer.Interval=1000000;
            timer.Start();
          while (true)
	       {
               if (timer.Interval == 0) break;

               Worker.ReportProgress(timer.Interval * 100 / 100); //Raise the ProgressChanged event.
	       }

            


        }


        private void button2_Click(object sender, EventArgs e)
        {
            while(true)
            {


            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

            button1.Enabled = true;
            progressBar1.Value = 0;
            Worker.RunWorkerAsync();

        
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Worker.CancelAsync();
            button3.Enabled = false;
        }
    }
}

推荐答案

请参阅此处以获取解决方案:
http://www.shabdar.org/cross-thread-operation-not-valid.html [^ ]

还有其他方法,但这是一种通用类型.

欢呼声
See here for a solution :
http://www.shabdar.org/cross-thread-operation-not-valid.html[^]

There are other ways but this is a generic kind.

Cheers


您无法在DoWork方法中访问任何控件.如果要访问任何控件(例如更改标签的文本,设置进度栏值等).它只能在ProgressChanged或RunWorkerCompleted方法中完成.

从代码中可以明显看出,您正在DoWork方法中更改标签的文本.

You can not access any control in the DoWork method. If you want to access any control (say changing the text of a label, setting progress bar value etc.). it can be done only in ProgressChanged or RunWorkerCompleted methods.

From your code, it is obvious that you are changing the text of a label in the DoWork method.

label1.Text = "BackGroundWorker Started.";
//Error Cross-thread operation not valid: Control ''label1'' accessed from a thread other than the thread it was created on.



不允许.
我建议您将这一步移到button1_Click中的Worker.RunWorkerAsync()之前.

根据经验,请记住您无法处理DoWork方法中的任何控件.
estys提出的建议也是正确的.在这种情况下,您只需调用要更改的控件的属性即可.

希望对您有帮助.
一切顺利.



It is not allowed.
I suggest you to move this step just before Worker.RunWorkerAsync() in button1_Click.

As a rule of thumb, remember that you can''t deal with any control in the DoWork method.
What estys has suggested is also correct. In that case you simply invoke the property of a control that you want to change.

Hope this helps you.
All the best.


在:
的地方 label1.Text ="BackGroundWorker已启动.";//错误跨线程操作无效:控件"label1"是从创建该线程的线程之外的线程访问的.


输入此代码:

SetLabelThreadSafe(label1,"BackGroundWorker已启动.");

私有无效SetLabelThreadSafe(Label lbl,字符串文本)
{
如果(lbl.InvokeRequired == true)
{
lbl.Invoke((MethodInvoker)delegate {lbl.Text = text;});
}
其他
{
lbl.Text = string.Empty;
}
}


我确定此代码可以正常运行.您可以为其他线程中存在的任何约束创建deligates.
At The Place of :
label1.Text = "BackGroundWorker Started.";//Error Cross-thread operation not valid: Control ''label1'' accessed from a thread other than the thread it was created on.


Put This Code :

SetLabelThreadSafe(label1, "BackGroundWorker Started.");

private void SetLabelThreadSafe(Label lbl, string text)
{
if (lbl.InvokeRequired == true)
{
lbl.Invoke((MethodInvoker)delegate { lbl.Text = text; });
}
else
{
lbl.Text = string.Empty;
}
}


I am sure This Code will run without any error. As The Same You can create the deligates for any contrals that exists in other thread.


这篇关于后台工作者错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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