[英]How do i change label in another form with backgroundworker process c#?
[英]C# backgroundworker loop change label text
我的表单中有一个Label
,并且想要每秒更改其文本。 我以为我需要BackgroundWorker
但是其中的while循环似乎不起作用。 循环的第一行完成了工作,但是在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);
}
}
而是使用Timer 。 考虑以下示例,其中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();
}
}
发生停止是因为您遇到System.InvalidOperationException
异常,该异常是由于您尝试从与创建控件元素不同的线程中操作控件元素而发生的。
为了解决您的问题,您可以使用Control.BeginInvoke 。 此方法将拉动主线程上的控件操纵的执行:
while (true)
{
ageLabel.BeginInvoke(new Action(() => { ageLabel.Text = "test"; }));
Thread.Sleep(1000);
ageLabel.BeginInvoke(new Action(() => { ageLabel.Text = "bla"; }));
Thread.Sleep(1000);
}
如果在Visual Studio中使用Windows窗体,建议查看输出窗口 。 诸如此类的异常将在此处显示。 :)
编辑:如果您只想按一定的时间间隔更新UI组件属性,则也可以使用Timer ,它是为此目的而构建的。 它在主UI线程上执行,因此不需要任何调用。
但是总的来说,这种想法仍然成立,如果您想从一个不同于创建线程的线程中操纵一个控件,那么您就需要调用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.