簡體   English   中英

使用Task.Unwrap來獲取內部任務

[英]Using Task.Unwrap to get to the inner task

我正在嘗試使用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();
    }

在實際項目中,我提供了Task<Task> ,其中每個內部任務都是通用任務。 我可以不使用Unwrap來訪問內部任務及其結果嗎?

您可以使用ContinueWith()來執行此操作,它將內部Task Task<YourType>Task<YourType> ,然后是Unwrap()

Task<bool> task4 = task2.ContinueWith(t => (Task<bool>)t.Result).Unwrap();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM