Click here to Skip to main content
16,004,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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;
        }
    }
}
Posted
Comments
Abhinav S 1-Feb-11 9:37am    
What's the error?
Pravin Patil, Mumbai 1-Feb-11 10:19am    
//Error Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.

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
 
Share this answer
 
v2
Comments
Pravin Patil, Mumbai 1-Feb-11 10:09am    
Very nice link...
Sergey Alexandrovich Kryukov 1-Feb-11 12:16pm    
This is a correct answer - my 5.
I should note that Pravin's answer is wrong in the part where it's said "impossible to access". It is possible via invocation of operation in UI thread, as shown in the example referenced.
--SA
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.


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.
 
Share this answer
 
Comments
sam, atlanta 1-Feb-11 10:07am    
It worked for me
Rahul Jain, Serious Coder 1-Feb-11 10:08am    
me tooo
Sergey Alexandrovich Kryukov 1-Feb-11 12:24pm    
Pravin, unfortunately your answer is wrong because of misleading statement which is simply not true: "can't deal with any control in the DoWork method".

When you comment "not allowed" it is still true, but next paragraph is false, even as a rule of thumb. And this is misleading, because "dealing with" a control from a function running in a different thread (as with DoWork) is practically very important.

It should be done via label1.Invoke(new Action<Label>((label)=>{labe.Text = "my text"}), label1).
A code sample provided by Estis shows that.
I would advise you to improve your answer, in order to avoid distributing a misconception.

--SA
Pravin Patil, Mumbai 2-Feb-11 0:54am    
I will take care of that SA.
Sorry for any misconception.
Sergey Alexandrovich Kryukov 2-Feb-11 3:13am    
Please, no sorry. I would be happy if it helps you.
--SA
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900