从另一个线程更新标签 [英] Update label from another thread
问题描述
我在使用另一个类线程写了更新的标签。
标签是在WinForm的主要内容类
I use a thread writing in another class for update a label. The label is contents in Winform Main class.
Scanner scanner = new Scanner(ref lblCont);
scanner.ListaFile = this.listFiles;
Thread trd = new Thread(new ThreadStart(scanner.automaticScanner));
trd.IsBackground = true;
trd.Start();
while (!trd.IsAlive) ;
trd.Join();
怎么可以看到,我通过标签的参考进入第二类的构造函数。
第二类(扫描仪),我有一个名为automaticScanner的方法应该更新与此代码标签:
How you can see, i pass the reference of label into constructor of the second class. In the second class(Scanner) i've a method called "automaticScanner" that should update the label with this code:
public Scanner(ref ToolStripStatusLabel _lblContatore)
{
lblCounter= _lblContatore;
}
Thread threadUpdateCounter = new Thread(new ThreadStart(this.UpdateCounter));
threadUpdateCounter.IsBackground = true;
threadUpdateCounter.Start();
while (!threadUpdateCounter .IsAlive) ;
threadUpdateCounter.Join();
private void AggiornaContatore()
{
this.lblCounter.Text = this.index.ToString();
}
我已经收到标签的更新这个错误:
I've receive this error on update of label:
跨线程操作无效:控制'主'从比它是在
Cross-thread operation not valid: Control 'Main' accessed from a thread other than the thread it was created on
我用.NET 4的Winform C#。
I use .net 4 with Winform C#.
非常感谢你的答案。
新闻:
的问题是这一行:
News: The problem is this line:
trd.Join();
这行挡住我的GUI和拉布勒没有更新。
有方法来控制线程的光洁度和更新标签直到结束?
谢谢
This line block my GUI and the lable was not update. There are methods to control the finish of thread and updating the label until the end? Thanks
推荐答案
您不能从非UI线程以外的任何其他线程更新UI。
使用此更新UI线程的线程。
You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.
private void AggiornaContatore()
{
if(this.lblCounter.InvokeRequired)
{
this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});
}
else
{
this.lblCounter.Text = this.index.ToString(); ;
}
}
请从本书要经过本章多获取线程的清晰图像:
Please go through this chapter and more from this book to get a clear picture about threading:
的http:// www.albahari.com/threading/part2.aspx#_Rich_Client_Applications
这篇关于从另一个线程更新标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!