Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Task.Unwrap to get to the inner task

I'm trying to access the inner task with Task.Unwrap and I'm 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 the real project, I'm provided with a list of Task<Task>, where each inner task is a generic task. Can I not use Unwrap to access the inner tasks and their results?

like image 994
avo Avatar asked Mar 10 '14 21:03

avo


People also ask

What does Task Unwrap do?

Unwrap(Task<Task>)Creates a proxy Task that represents the asynchronous operation of a Task<Task> (C#) or Task (Of Task) (Visual Basic).

What is the difference between Task run and Task factory StartNew?

Run(action) internally uses the default TaskScheduler , which means it always offloads a task to the thread pool. StartNew(action) , on the other hand, uses the scheduler of the current thread which may not use thread pool at all!

How to Start New Task in c#?

To start a task in C#, follow any of the below given ways. Use a delegate to start a task. Task t = new Task(delegate { PrintMessage(); }); t. Start();

What is a nested task?

A nested task is just a Task instance that is created in the user delegate of another task. A child task is a nested task that is created with the AttachedToParent option. A task may create any number of child and/or nested tasks, limited only by system resources.


Video Answer


1 Answers

You can do this by using ContinueWith(), which will cast the inner Task to Task<YourType>, followed by Unwrap():

Task<bool> task4 = task2.ContinueWith(t => (Task<bool>)t.Result).Unwrap();
like image 178
svick Avatar answered Oct 20 '22 16:10

svick