我在Winform中使用后台工作线程,在Do_Work事件中计算某些内容,同时我希望能够更新主/UI线程中的标签。如何实现?
我想要在Do_Work事件中更新我的标签...
我在Winform中使用后台工作线程,在Do_Work事件中计算某些内容,同时我希望能够更新主/UI线程中的标签。如何实现?
我想要在Do_Work事件中更新我的标签...
public void UpdateLabel(String text){
if (label.InvokeRequired)
{
label.Invoke(new Action<string>(UpdateLabel), text);
return;
}
label.Text = text;
}
在你的Do_Work
方法中,你可以使用对象的Invoke()
方法在其UI线程上执行委托,例如:
this.Invoke(new Action<string>(UpdateLabel), newValue);
...然后确保在您的类中添加一个像这样的方法:
private void UpdateLabel(string value)
{
this.lblMyLabel.Text = value;
}
希望这可以帮到你:
int x = 0;
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = x.ToString();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
x++;
//you can put any value
backgroundWorker1.ReportProgress(0);
}
private void button6_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
public static class ControlExtensions
{
public static void UpdateControlText(this Control control, string text)
{
if (control.InvokeRequired)
{
_ = control.Invoke(new Action<Control, string>(UpdateControlText), control, text);
}
control.Text = text;
}
public static void UpdateAsync(this Control control, Action<Control> action)
{
if(control.InvokeRequired)
{
_ = control.Invoke(new Action<Control, Action<Control>>(UpdateAsync), control, action);
}
action(control);
}
}
你可以像这样使用方法:
TextBox1.UpdateControlText(string.Empty); // Just update the Text property
// Provide an action/callback to do whatever you want.
Label1.UpdateAsync(c => c.Text = string.Empty);
Button1.UpdateAsync(c => c.Text == "Login" ? c.Text = "Logout" : c.Text = "Login");
Button1.UpdateAsync(c => c.Enabled == false);
{
x++;
//you can put any value
Action = act =()=>
{
label.Text = Convert.ToString(x);
};
if (label.InvokeRequired)
label.BeginInvoke(act);
else
label.Invoke(act);
backgroundWorker1.ReportProgress(0);
}