~ Ready? ~
When you perform a background operation - that is, some actual CPU work that you push off to a background thread - it’s usually done to calculate some result. Today we’re looking at how
BackgroundWorker handle returning results.
~ Fight! ~
It’s pretty straightforward to return values from a
BackgroundWorker; just set the
DoWorkEventArgs.Result property and then you can pick up the results from
The biggest awkwardness caused by this code is the loss of type information of the result. Both
RunWorkerCompletedEventArgs.Result are of type
object, so you have to cast it to the correct type when retrieving the result.
The lambda passed to
Task.Run can simply return a value:
Task.Run code uses the natural
return syntax, is strongly typed, and is more concise than
BackgroundWorker. This round clearly goes to