user1683382 user1683382 - 1 month ago 21
C# Question

C# in Async Task change Label Text

The following Code does not change the Text and stops executing the Task

private void button1_Click(object sender, EventArgs e)
{
label1.Text = "Test";
Task.Run(() => MyAsyncMethod());
}

public async Task MyAsyncMethod()
{
label1.Text = "";
//everything from here on will not be executed
}


would be really handy if you could use async together with the UI

Answer

for accessing a GUI control through a second thread you need to invoke. following example shows how to set a label's text properly

  private void setLabel1TextSafe(string txt)
  { 
       if(label1.InvokeRequired)
       {label1.Invoke(new Action(()=>label1.Text=txt)));return;}
       label1.Text=txt;
  }

I hope this solves your problem