| title | ms.custom | ms.date | ms.prod | ms.reviewer | ms.suite | ms.technology | ms.tgt_pltfrm | ms.topic | helpviewer_keywords | ms.assetid | caps.latest.revision | author | ms.author | manager | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
How to: Unwrap a Nested Task |
03/30/2017 |
.net |
dotnet-standard |
article |
|
a0769dd2-0f6d-48ca-8418-a9d39de7f450 |
11 |
rpetrusha |
ronpet |
wpickett |
How to: Unwrap a Nested Task
You can return a task from a method, and then wait on or continue from that task, as shown in the following example:
[!code-csharpTPL_Unwrap#01] [!code-vbTPL_Unwrap#01]
In the previous example, the xref:System.Threading.Tasks.Task%601.Result%2A property is of type string (String in Visual Basic).
However, in some scenarios, you might want to create a task within another task, and then return the nested task. In this case, the TResult of the enclosing task is itself a task. In the following example, the Result property is a Task<Task<string>> in C# or Task(Of Task(Of String)) in Visual Basic.
[!code-csharpTPL_Unwrap#02] [!code-vbTPL_Unwrap#02]
Although it is possible to write code to unwrap the outer task and retrieve the original task and its xref:System.Threading.Tasks.Task%601.Result%2A property, such code is not easy to write because you must handle exceptions and also cancellation requests. In this situation, we recommend that you use one of the xref:System.Threading.Tasks.TaskExtensions.Unwrap%2A extension methods, as shown in the following example.
[!code-csharpTPL_UnWrap#03] [!code-vbTPL_UnWrap#03]
The xref:System.Threading.Tasks.TaskExtensions.Unwrap%2A methods can be used to transform any Task<Task> or Task<Task<TResult>> (Task(Of Task) or Task(Of Task(Of TResult)) in Visual Basic) to a Task or Task<TResult> (Task(Of TResult) in Visual Basic). The new task fully represents the inner nested task, and includes cancellation state and all exceptions.
Example
The following example demonstrates how to use the xref:System.Threading.Tasks.TaskExtensions.Unwrap%2A extension methods.
[!code-csharpTPL_UnWrap#04] [!code-vbTPL_UnWrap#04]
See Also
xref:System.Threading.Tasks.TaskExtensions?displayProperty=nameWithType
Task-based Asynchronous Programming