跨线程操作无效:从创建的线程以外的线程访问控制’label1′

可能重复:
为什么我会收到此错误:“跨线程操作无效:控制从其创建的线程以外的线程访问的lbFolders。”?

我是winforms的新手。在我的代码中,我正在使用for循环更新进度条,现在我需要以循环计数的forms更新Label,如下所示 –

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

但是在访问label1时,它会抛出错误 –

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

如何更新label1的文本

在进度处理程序中而不是在工作线程内更新标签。

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

您只能从创建它的线程(即UI线程)访问该控件。 在其他线程(如BackgroundWorker)中,您需要使用Control.BeginInvoke 。

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

backgroundWorker1_DoWork在与主UI线程分开的线程上运行。

所以当你打电话时:

 label1.Text = "Trade" + i; 

在backgroundWorker1_DoWork里面你的应用程序会抛出跨线程exception,因为你报告了你的worker的进度,你可以在backgroundWorker1_ProgressChanged方法中更新label1.Text值