I have a simple BackgroundWorker
that should generate results, but I don't know how to get them back to my calling method. I have read a number of answers, and they all show me how the RunWorkerCompleted
event can receive the results of the DoWork
event handler, and to prove this they show a message box with the result. That's all good, but how do I get a result back to the actual method that called RunWorkerAsync
?
myResult=myBackGroundWorker.RunWorkerAsync(); // This obviously doesn't compile
This answer in particular has been very useful:
How to make BackgroundWorker return an object
but I still don't know how to access the results. This answer also mentions the use of a delegate:
BackgroundWorker Return A Value?
but I don't understand if this would solve my problem, or if I would still just get the result inside the RunWorkCompleted event handler.
Short answer: you can't.
Think about what it means to return the value back to the method that called RunWorkerAsync
. This would mean that the method has to pause its execution, wait for the background worker to complete its work, then continue again. But you still want other methods to run during the waiting, otherwise the UI would freeze.
Does that sound familiar to you? That's basically what an async
method does when it encounters an await
expression!
BackgroundWorker
is quite an old API, and there wasn't the fancy feature of async/await when it came out (async/await is a language feature anyway), which is why it uses events to do the trick. Back then, there wasn't a way to do an operation asynchronously, and return a value back to the caller elegantly.
Now that we have async/await, you can use it to do what you want:
someReuslt = await Task.Run(() => { ... });
If you haven't heard about async/await at all, this is a good place to start.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.