C# Background worker setting e.Result in DoWork and getting value back in WorkCompleted

自作多情 提交于 2019-11-29 09:12:33

From MSDN:

If the operation completes successfully and its result is assigned in the DoWork event handler, you can access the result through the RunWorkerCompletedEventArgs.Result property.

and:

Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. If an exception was raised or if the operation was canceled, accessing the Result property raises an exception.

So if it doesn't complete successfully (i.e. you cancel it) it looks like it won't work. Perhaps consider returning your cancellation-details as the result (as success) for your abort case, an detecting the difference in the completion handler?

The Result property is meant to represent the result of a completed operation. You've set Cancel to true, meaning that the operation was cancelled, therefore there shouldn't be a result.

It sounds like you should encode the "I aborted because something was wrong" into your result, or throw an exception which will be set as the Error property in the result instead - Cancel is meant to be set if the worker noticed that the call was cancelled externally.

The docs for RunWorkerCompletedEventArgs.Result state:

Your RunWorkerCompleted event handler should always check the Error and Cancelled properties before accessing the Result property. If an exception was raised or if the operation was canceled, accessing the Result property raises an exception.

The "Exceptions" part of the documentation also states that it will throw an exception if Cancelled is true.

It's most probably because the code Cancels the work instead of completing it. So try accessing the result in the if(!e.Cancel) branch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!