为什么New Task <object>((Func <task <object>&gt;)(async()=&gt; {})在新的Task <foo>(...)没有时工作?

时间:2015-12-08 02:51:23

标签: c# multithreading asynchronous

为什么new Task<object>( (Func<Task<object>>)( async ( ) => { } )new Task<Foo>( ... )没有时才会有效?

这有效:

private static Task<object> Works( ) {
    return new Task<object>( ( Func<Task<object>> )( async ( ) => {
        return new object( );
    } ), new CancellationTokenSource( ).Token );
}

但这不是:

private static Task<Foo> Doesnt( ) {
    return new Task<Foo>( (Func<Task<Foo>>)(async ( ) =>{
        return new Foo( );
    } ), new CancellationTokenSource( ).Token );
}

Foo 替换为非对象(或我正在猜测的任何其他原语)的任何内容,您将看到在红色波浪线上得到相同的错误消息:The best overloaded method match for 'System.Threading.Task.Task<Foo>.Task(object, System.Threading.Tasks.TaskCreationOptions)' has some invalid arguments

我甚至看到它所引用的重载方法......但是为什么我认为我在尝试使用Func<Task<Foo>>但是 NOT 当我使用Func<Task<object>> ?????

这适用于对象(或对象),但与我的类一起使用FAILS。我甚至尝试了另一个类对象(Window),但失败了。

修改

为了回应第一位未编译的声明,我已经能够编译以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncFlubbery {
    class Program {

        private static Task<object> Works( ) {
            return new Task<object>( ( Func<Task<object>> )( async ( ) => {
                return new object( );
            } ), new CancellationTokenSource( ).Token );
        }

        static void Main( string[ ] args ) {
            Works( ).Start( );
            Console.WriteLine( "Press Enter To Begin..." );
            Console.ReadLine( );
        }
    }
}

1 个答案:

答案 0 :(得分:4)

这是一种类型转换的简单案例。

归结为此代码:

Func<Task<object>> fto = null;
Func<object> fo = fto; //this is a fine cast

Func<Task<Foo>> ftf = null;
Func<Foo> ff = ftf; //this is **NOT** a fine cast

由于Task<object>派生自object,所以第一次演员阵容就行了。

Task<Foo> 来自Foo,因此投射无效。

因此,即使第一个代码编译它也无法在运行时按预期工作。这两段代码最终都有问题。