跨线程操作无效:控制“label1"从创建它的线程以外的线程访问 [英] Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on
问题描述
可能的重复:
为什么我会收到此错误:“跨线程操作无效:控制 lbFolders 是从创建它的线程以外的线程访问的.”?
我是 winforms 的新手.在我的代码中,我正在使用 for 循环更新进度条,现在我需要以循环计数的形式更新标签,如下所示 -
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 -
公共部分类 Form1 : 表单{公共 Form1(){InitializeComponent();
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 时,它抛出错误 -
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.
如何更新 label1 的文本
How can I update text of label1
推荐答案
在进度处理程序中而不是在工作线程中更新标签.
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);
}
这篇关于跨线程操作无效:控制“label1"从创建它的线程以外的线程访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!