设置使用线程创建的控件的属性 [英] Setting the properties of a control created using a thread

查看:51
本文介绍了设置使用线程创建的控件的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个C#程序,其中尝试暗示使用线程.我想在状态栏上有一个标签,我想根据当前线程的工作方式和状态来设置一条消息.
但是,只要我尝试在除创建它的主线程之外的其他线程之一中设置控件(标签)的text属性,就会收到错误消息,提示我无法在ID不同的线程中设置控件的属性从创建控件的线程(标签)开始.
我尝试使用

I am writing a C# program in which I try implying the use of threads. There is a label on a status bar that I would like to set a message based on the workings and the status of the current thread.
But anytime i try setting the text property of the control (label) in one of the threads other than the main thread that created it, I get the error message that i can not set the properties of the control in a thread whose ID is different from the thread that created the control (label).
I try using the

invokeRequired()

方法只是发现ToolStripLabel没有任何具有该名称的方法.
如果有人在那里能紧急帮助我,我将感到高兴.谢谢!

method only to found out that the ToolStripLabel does not have any method with that name.
I will be glad if some one there can help me urgently. Thank you!

推荐答案

您只能在UI线程中更新UI控件.看看这个.还有一个很好的例子: http://msdn.microsoft. com/en-us/library/system.windows.forms.control.invokerequired.aspx [
You can update the UI controls only in the UI thread. Have a look at this. There''s a good example also: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx[^]


当我开始使用.NET时,我假设任何UI元素需要从线程调用"的方法将实现InvokeRequired属性.但是,这是不正确的,并且存在一些轻量级UI元素,例如Toolstrip项和TreeView节点,它们不是从Control类派生的,但仍应仅从UI线程进行更新.

那么,如果没有Invoke方法,该怎么办?很好的答案是使用宿主窗体上存在的任何控件的Invoke/InvokeRequired,甚至窗体本身也是如此.

When I started using .NET I made the assumption that any UI element that required ''Invoking'' from a thread would implement the InvokeRequired property. However this is not true and there are some lightweight UI elements such as Toolstrip items and TreeView nodes which are not derived from the Control class but still should only be updated from the UI thread.

So what should be done if there is no Invoke method? Well the answer is to use the Invoke/InvokeRequired of any control present on the host form, even the form itself.

private delegate void LabelUpdateDelegate(String text);

private void UpdateStatusLabel(String text) {
  if (this.InvokeRequired) {
    this.Invoke(new LabelUpdateDelegate(UpdateStatusLabel), text);
  } else {
    status.Text = text;
  }
}



艾伦.



Alan.


这篇关于设置使用线程创建的控件的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆