Why InvalidCastException when awaiting Task-returning method?

有些话、适合烂在心里 提交于 2019-11-29 11:47:15

As it sometimes turns out, I managed to find out the answer to the question while posting it here. Thought I'd share it to save someone else from headache...

The problem stems from my use of dynamic, or rather, the (in my opinion) slightly limited and broken way dynamic works in C#/.NET as of yet. If I rephrase my code like this:

await (Task)DownloadFileAsync(file, targetFolder, uri);

...it works flawlessly.

The thing here is that since one of my parameters (file is dynamic), this will be a dynamic operation. And return values seem to be somehow "messed up" from dynamic operations; the CLR is simply unable to deduce from the code above whether the method returns Task or Task<T> (or so I guess). It therefore fails trying to cast the result to an INotifyCompletion instance - hence, the exception.

Thanks a lot, Microsoft. ;)
(I think the main problem here is that the exception message was very unclear, in my opinion...)

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