Update progress bar from Task.Run async

后端 未结 2 767
误落风尘
误落风尘 2021-02-10 09:34

I have a method to generate software activation key from User Information:

private async void GenerateAsync()
        {
            await Task.Run(() =>
              


        
相关标签:
2条回答
  • 2021-02-10 09:49

    You should use the more modern IProgress<T>/Progress<T> types:

    var progress = new Progress<int>(value => { progressBar.Value = value; });
    await Task.Run(() => GenerateAsync(progress));
    
    void GenerateAsync(IProgress<int> progress)
    {
      ...
      progress?.Report(13);
      ...
    }
    

    This is better than Invoke because it doesn't tie your business logic (GenerateAsync) to a particular UI, or to any UI at all.

    0 讨论(0)
  • 2021-02-10 10:05

    I use this method in Winforms:

    progressBar1.Invoke((Action)(() => progressBar1.Value=50))
    
    0 讨论(0)
提交回复
热议问题