I would like to know the difference between using EventHandler<T>
and Progress<T>
. Are there any situations in which one is a better choice?
When dealing with async Tasks
I often see an EventHandler<T> progressChangedCallback
that people use to subscribe to a ProgressChanged
event of an object and report progress change to e.g. a progress bar on the UI. I also see people passing IProgress<T>
instances to the Tasks
as parameters. The difference is that they don't invoke an event, they call the IProgress<T>.Report()
method instead.
CodePudding user response:
They're different mechanisms. An event is defined on a class, and a IProgress<T>
is passed to the async operation itself. An event might make more sense when only 1 async operation is happening at a time, and the progress of every such operation needs to be displayed in the same way, as the UI needs to subscribe to a single event once, and all progress updates from it are handled the same way. An IProgress<T>
might make more sense when you can have multiple async operations on the go at once, as it lets you understand which progress is being reported by which operation.
Note that the Progress<T>
does the nice thing of dispatching progress updates back to the UI thread (if used in the right way), but events don't do this.
(This answer was posted initially as a comment by @canton7)