代表和设置标签

时间:2015-04-23 17:10:33

标签: c# .net multithreading winforms

因此,我使用此代码的总体目标是从不同的线程(以安全的方式)设置标签的文本属性。

namespace csDinger3
{
    public delegate void setlblStarted_txt(string text);

    public partial class ClientUI : Form
    {
        public void setlblStarted_txt(string text)
        {
            var setlblStarted a = new setlblStarted(setlblStarted_txt);
            if (this.lblStarted.InvokeRequired)
            {
                this.Invoke(a, new object[] { text });
            }
            else
            {
                this.lblStarted.Text = text;
            }
        }
    }
}

致电代码:

namespace csDinger3
{
    public class Program
    {
        // Some code that's not relevant
        public static void updateText(Int32 number)
        {
            setlblStarted x = new setlblStarted(ClientUI.setlblStarted_txt);
            x(number.ToString());
        }
    }
}

根据我的理解(如果我错了请纠正我),我需要创建setlblStarted_txt的新实例,在方法setlblStarted_txt指出新实例,但问题是当前ClientUI.setlblStarted_txt不是静态的,并且需要对象引用。

我已尝试使用ClientUI c = new ClientUI();,但这不起作用(因为它正在创建表单的新实例?)

我做错了什么,如果可能的话,你能帮助我理解为什么吗?

2 个答案:

答案 0 :(得分:0)

在.Net 4.0中,您可以使用操作:

if (InvokeRequired)
{
     Invoke(new Action<string>(updateText), "some text");
}
else
{
     updateText("some text");
}

此外,void updateText(string text)不需要是静态的。

答案 1 :(得分:0)

据我了解,您正尝试使用MethodInvoker委托更新文字。我建议你改变这种方法来简化你的代码:

namespace csDinger3
{
    public class Program
    {
        static ClientUI aForm;

        static void Main()
        {
             aForm = new ClientUI();
             aForm.Show();
        }
        // Some code that's not relevant
        public static void updateText(Int32 number)
        {
            aForm.setlblStarted_txt(number.ToString());
        }

public partial class ClientUI : Form
{
    public void setlblStarted_txt(string text)
    {
        if (lblStarted.InvokeRequired)
        {
            Invoke(new EventHandler(delegate
            {
                lblStarted.Text = text
            }));
        }
        else
        {
            lblStarted.Text = text;
        }
    }

使用ThreadPoolSynchronizationContextDispatcher(在WPF中)可以实现相同的行为。请参阅本教程以便更好地理解: