如何从另一个类c#更新标签

时间:2015-07-28 04:39:59

标签: c#

如果我将threadtest()放在form1.cs中它将正常工作,但我想移动到另一个类,它将显示错误。这是错误的屏幕截图

enter image description here

public partial class Form1 : Form
{
    Thread thread;
    bool loop = true;
    volatile bool _cancelPending = false;
    Stopwatch regularSW = new Stopwatch();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        thread = new Thread(new ThreadStart(() => threadtest()));
        thread.Start();
    }
    public void threadtest()
    {
        while (loop)
        {
            regularSW.Start();
            Thread.Sleep(5000);
            regularSW.Stop();
            label1.Text = "Sleep in: " + regularSW.Elapsed + Environment.NewLine;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

Form1类是Windows窗体的代码隐藏类。名为label1的标签未在Class1中定义。

你能使用活动吗?

定义可以更新的其他参数。

public event Action<string> onStatusChange;
public void threadtest()
{
    var status = "";
    while (loop)
    {
        regularSW.Start();
        Thread.Sleep(5000);
        regularSW.Stop();
        if(null != onStatusChange)
        {
             onStatusChange("Sleep in: " + regularSW.Elapsed + Environment.NewLine);
        }            
    }
}

在Form1类中:

var class1 = new Class1();
class1.onStatusChange += (status) => { label1.Text = status; };
class1.threadtest();      

答案 1 :(得分:-1)

尝试以下代码。 在Form1类button1_Click中添加以下代码:

public partial class Form1 : Form
{
    private void button1_Click(object sender, EventArgs e)
    {
    Class1 class1Object = new Class1();
    thread = new Thread(new ThreadStart(() => class1Object.threadtest(this)));
    thread.Start();
   }
}

现在更改您的class1 threadtest()功能,如下所示:

class Class1
{
     public void threadtest(Form1 form)
     {
    while (loop)
    {
        regularSW.Start();
        Thread.Sleep(5000);
        regularSW.Stop();
        form.label1.Text = "Sleep in: " + regularSW.Elapsed + Environment.NewLine;
    }
}

}