C# async/await Progress event on Task<> object

前端 未结 4 1901
一个人的身影
一个人的身影 2020-12-02 17:22

I\'m completely new to C# 5\'s new async/await keywords and I\'m interested in the best way to implement a progress event.

Now I\'d prefer

4条回答
  •  既然无缘
    2020-12-02 17:58

    The recommended approach is described in the Task-based Asynchronous Pattern documentation, which gives each asynchronous method its own IProgress:

    public async Task PerformScanAsync(IProgress progress)
    {
      ...
      if (progress != null)
        progress.Report(new MyScanProgress(...));
    }
    

    Usage:

    var progress = new Progress();
    progress.ProgressChanged += ...
    PerformScanAsync(progress);
    

    Notes:

    1. By convention, the progress parameter may be null if the caller doesn't need progress reports, so be sure to check for this in your async method.
    2. Progress reporting is itself asynchronous, so you should create a new instance of your arguments each time you call (even better, just use immutable types for your event args). You should not mutate and then re-use the same arguments object for multiple calls to Progress.
    3. The Progress type will capture the current context (e.g., UI context) on construction and will raise its ProgressChanged event in that context. So you don't have to worry about marshaling back to the UI thread before calling Report.

提交回复
热议问题