Using Task.Unwrap to complete an internal task

I am trying to access an internal task using Task.Unwrap, and I am getting this error:

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]'.

To reproduce the problem:

    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();
    }

In a real project, I’m given a list Task<Task>where each internal task is a common task. Can I use Unwrapto access internal tasks and their results?

+4
source share
1 answer

, ContinueWith(), Task Task<YourType>, Unwrap():

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

Source: https://habr.com/ru/post/1531056/


All Articles