Cross-thread operation not valid: Control 'lab

2020-07-22 18:53发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
Why am I getting this error:“Cross-thread operation not valid: Control lbFolders accessed from a thread other than the thread it was created on.”?

I am new in winforms.In my code I am updating progress bar with for loop and now I need to update a Label in the form the loop count as shown below -

public partial class Form1 : Form { public Form1() { InitializeComponent();

        Shown += new EventHandler(Form1_Shown);

        // To report progress from the background worker we need to set this property
        backgroundWorker1.WorkerReportsProgress = true;
        // This event will be raised on the worker thread when the worker starts
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        // This event will be raised when we call ReportProgress
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    void Form1_Shown(object sender, EventArgs e)
    {
        // Start the background worker
        backgroundWorker1.RunWorkerAsync();
    }


    // On worker thread so do our thing!
    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Your background task goes here
        for (int i = 0; i <= 100; i++)
        {
            label1.Text = "Trade" + i;
            // Report progress to 'UI' thread
            backgroundWorker1.ReportProgress(i);
            // Simulate long task
            System.Threading.Thread.Sleep(100);
        }
    }
    // Back on the 'UI' thread so we can update the progress bar
    void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        // The progress percentage is a property of e
        progressBar1.Value = e.ProgressPercentage;
    }

}

but while accessing label1,it is throwing error -

Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.

How can I update text of label1

回答1:

Update your label in your progress handler instead of inside the worker thread.

// On worker thread so do our thing! 
 void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
 { 
     // Your background task goes here 
     for (int i = 0; i <= 100; i++) 
     { 
         // Report progress to 'UI' thread 
         backgroundWorker1.ReportProgress(i); 
         // Simulate long task 
         System.Threading.Thread.Sleep(100); 
     } 
 } 
 // Back on the 'UI' thread so we can update the progress bar - and our label :)
 void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
 { 
     // The progress percentage is a property of e 
     progressBar1.Value = e.ProgressPercentage; 
     label1.Text = String.Format("Trade{0}",e.ProgressPercentage);
 } 


回答2:

You can only access the control from the thread where it was created(that is, the UI thread). In other threads(like your BackgroundWorker), you need to use Control.BeginInvoke.

label1.BeginInvoke(delegate { label1.Text = "Trade" + i; });


回答3:

The backgroundWorker1_DoWork runs on a separate thread from the main UI thread.

So when you call:

label1.Text = "Trade" + i;

inside backgroundWorker1_DoWork your application will throw the Cross-thread exception, because you're reporting the progress of your worker you can update the label1.Text value in the backgroundWorker1_ProgressChanged method