How can I efficiently update the UI from an async method?

前端 未结 1 868
故里飘歌
故里飘歌 2020-12-18 11:48

I\'m using a ProgressBar with binding to show the progress when receiving a file from a remote device.



        
相关标签:
1条回答
  • 2020-12-18 12:30

    The problem is I have the file transfer method in a different async method

    That doesn't necessarily follow. You shouldn't need to use CoreDispatcher explicitly. Asynchronous methods resume on the UI thread by default.


    For progress reporting, you should use IProgress<T>. You can use it with a structure to report progress, as such:

    public struct ProgressReport
    {
      public double Progress { get; set; }
      public double FileSize { get; set; }
    }
    
    async Task FileTransferAsync(IProgress<ProgressReport> progress)
    {
      ...
      if (progress != null)
      {
        progress.Report(new ProgressReport
        {
          Progress = (double)i,
          FileSize = fileSize
        });
      }
      ...
    }
    

    Then you can consume it with an IProgress<T> implementation. Since you need UI throttling, you can use one that I wrote that has built-in throttling:

    using (var progress = ObservableProgress<ProgressReport>.CreateForUi(value =>
        {
            ProgressFileReceive = (double)value.Progress / value.FileSize * 100;
        }))
    {
        await FileTransferAsync(progress);
    }
    
    0 讨论(0)
提交回复
热议问题