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
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:
progress
parameter may be null
if the caller doesn't need progress reports, so be sure to check for this in your async
method.Progress
.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
.