Why InvalidCastException when awaiting Task-returning method?

前端 未结 1 745
南笙
南笙 2020-12-19 22:18

(The real title of the question should be \"Why do I get a \'Unable to cast object of type \'System.Runtime.CompilerServices.TaskAwaiter`1[System.Runtime.CompilerServices.Vo

相关标签:
1条回答
  • 2020-12-19 22:41

    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...)

    0 讨论(0)
提交回复
热议问题