使用Task.Unwrap来获取内部任务

avo*_*avo 6 .net c# task task-parallel-library

我正在尝试访问内部任务,Task.Unwrap我收到此错误:

System.InvalidCastException: Unable to cast object of type 
'System.Threading.Tasks.UnwrapPromise`1[System.Threading.Tasks.TaskExtensions+VoidResult]' 
to type 'System.Threading.Tasks.Task`1[System.Boolean]'.

重现问题:

    static void Main(string[] args)
    {
        var tcs = new TaskCompletionSource<bool>();
        tcs.SetResult(true);
        Task task1 = tcs.Task;

        Task<Task> task2 = task1.ContinueWith(
            (t) => t, TaskContinuationOptions.ExecuteSynchronously);

        Task task3 = task2.Unwrap();

        try
        {
            Task<bool> task4 = (Task<bool>)task3;

            Console.WriteLine(task4.Result.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        Console.ReadLine();
    }
Run Code Online (Sandbox Code Playgroud)

在真实项目中,我提供了一个列表Task<Task>,其中每个内部任务都是通用任务.我可以不用Unwrap来访问内部任务及其结果吗?

svi*_*ick 7

您可以通过使用ContinueWith(),将内部强制转换TaskTask<YourType>,然后执行此操作Unwrap():

Task<bool> task4 = task2.ContinueWith(t => (Task<bool>)t.Result).Unwrap();
Run Code Online (Sandbox Code Playgroud)