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?
Unwrap(Task<Task>)Creates a proxy Task that represents the asynchronous operation of a Task<Task> (C#) or Task (Of Task) (Visual Basic).
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!
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();
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With