Update progress bar from Task.Run async

后端 未结 2 768
误落风尘
误落风尘 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/Progress types:

    var progress = new Progress(value => { progressBar.Value = value; });
    await Task.Run(() => GenerateAsync(progress));
    
    void GenerateAsync(IProgress 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.

提交回复
热议问题