C# in Async Task change Label Text

前端 未结 5 743
清酒与你
清酒与你 2021-01-03 09:50

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

private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = \         


        
5条回答
  •  失恋的感觉
    2021-01-03 10:56

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

    The design of async was carefully done so you can use it naturally with the UI.

    in my code i run a function that does a lot of IO and stuff that takes a long time

    If you have asynchronous I/O methods (which you should), then you can just do this:

    private async void button1_Click(object sender, EventArgs e)
    {
      label1.Text = "Test";
      await MyMethodAsync();
    }
    
    public async Task MyMethodAsync()
    {
      label1.Text = "";
      await ...; // "lot of IO and stuff"
      label1.Text = "Done";
    }
    

    That's the most natural approach.

    However, if you need to run code on a background thread (e.g., it's actually CPU-bound, or if you just don't want to make your I/O operations asynchronous like they should be), then you can use IProgress:

    private void button1_Click(object sender, EventArgs e)
    {
      label1.Text = "Test";
      var progress = new Progress(update => { label1.Text = update; });
      await Task.Run(() => MyMethod(progress));
    }
    
    public void MyMethod(IProgress progress)
    {
      if (progress != null)
        progress.Report("");
      ...; // "lot of IO and stuff"
      if (progress != null)
        progress.Report("Done");
    }
    

    Under no circumstances should modern code use Control.Invoke or (even worse) Control.InvokeRequired.

提交回复
热议问题