简体   繁体   English

C#backgroundworker循环更改标签文本

[英]C# backgroundworker loop change label text

I have a Label in my form and want to change its text every second. 我的表单中有一个Label ,并且想要每秒更改其文本。 I thought that a BackgroundWorker is what I need but the while loop in it doesn't seem to work. 我以为我需要BackgroundWorker但是其中的while循环似乎不起作用。 The first line in the loop does its job but after a Thread.Sleep the loop seems to stop. 循环的第一行完成了工作,但是在Thread.Sleep ,循环似乎停止了。

public MainForm()
{           

    InitializeComponent();

    backgroundWorker1.DoWork += new DoWorkEventHandler(getFrame);

    backgroundWorker1.RunWorkerAsync();
}

void getFrame(object sender, DoWorkEventArgs e)
{
    while(true) {
        ageLabel.Text = "test";
        Thread.Sleep(1000);
        ageLabel.Text = "baa";
        Thread.Sleep(1000);
    }
}

Instead, use a Timer . 而是使用Timer Consider this example, where label1 is a simple Label control on a WinForm: 考虑以下示例,其中label1是WinForm上的一个简单Label控件:

public partial class Form1 : Form
{
    Timer _timer = new Timer();

    public Form1()
    {
        InitializeComponent();

        _timer.Interval = 1000;
        _timer.Tick += _timer_Tick;
        _timer.Start();
    }

    private void _timer_Tick(Object sender, EventArgs e)
    {
        label1.Text = DateTime.Now.ToString();
    }
}

The stopping occurs because you run into a System.InvalidOperationException exception which occurs because you try to manipulate a control element from a different thread than it was created on. 发生停止是因为您遇到System.InvalidOperationException异常,该异常是由于您尝试从与创建控件元素不同的线程中操作控件元素而发生的。

To solve your problem you can use Control.BeginInvoke . 为了解决您的问题,您可以使用Control.BeginInvoke This method will pull the execution of the control manipulation on the main thread: 此方法将拉动主线程上的控件操纵的执行:

while (true)
{
    ageLabel.BeginInvoke(new Action(() => { ageLabel.Text = "test"; }));
    Thread.Sleep(1000);
    ageLabel.BeginInvoke(new Action(() => { ageLabel.Text = "bla"; }));
    Thread.Sleep(1000);
}

If working with windows forms in visual studio it is adviseable to look into the output window . 如果在Visual Studio中使用Windows窗体,建议查看输出窗口 Exceptions such as this one will be shown there. 诸如此类的异常将在此处显示。 :) :)

EDIT: if you simply want to update the UI component property on a timed intervals, you could as well use a Timer , which was built for this exact purpose. 编辑:如果您只想按一定的时间间隔更新UI组件属性,则也可以使用Timer ,它是为此目的而构建的。 It is executed on the main UI thread and thus does not need any invocation. 它在主UI线程上执行,因此不需要任何调用。

But in general the idea still holds, if you want to manipulate a control from a different thread than it was created on, then you need invocation! 但是总的来说,这种想法仍然成立,如果您想从一个不同于创建线程的线程中操纵一个控件,那么您就需要调用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM