Why InvalidCastException when awaiting Task-returning method?

左心房为你撑大大i 提交于 2019-11-28 05:40:03

问题


(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.VoidTaskResult]' to type 'System.Runtime.CompilerServices.INotifyCompletion'", but unfortunately this is too long for StackOverflow. :)

Hi,

I'm getting really peculiar problems when trying to await the execution of a method of mine. The calling code looks like this (excerpt):

    private async Task DownloadAddonFileAsync(dynamic addon, dynamic file, string targetFolder)
    {
        // ...
        await DownloadFileAsync(file, targetFolder, uri);

The DownloadFileAsync looks like this:

    protected async Task DownloadFileAsync(dynamic file, string targetFolder, string uri)
    {
        // ...
        var fileBytes = await AppLoaderRestClient.GetAsync<byte[]>(uri);

The AppLoaderRestClient.GetAsync(), in turn, looks like this:

    public static async Task<T> GetAsync<T>(string uri)
    {
        // ...
        if (typeof (T) == typeof (byte[]))
        {
            var result = await webClient.DownloadDataTaskAsync(uri);
            return (T) (object) result;
        }

So, there is actually a chain of Tasks here - the "inner" Task will be a Task, which will then be propagated up to the caller, and converted to a Task (i.e. a Task without a result). I presume this could be causing the issue at hand?

If I change the outermost code to this:

        var task = DownloadFileAsync(file, targetFolder, uri);
        task.Wait();

...it works flawlessly. Why?


回答1:


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



来源:https://stackoverflow.com/questions/19157258/why-invalidcastexception-when-awaiting-task-returning-method

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