Skip to content

Latest commit

 

History

History
43 lines (30 loc) · 2.88 KB

how-to-unwrap-a-nested-task.md

File metadata and controls

43 lines (30 loc) · 2.88 KB
description title ms.date dev_langs helpviewer_keywords ms.assetid
Learn more about: How to: Unwrap a Nested Task
How to: Unwrap a Nested Task
03/30/2017
csharp
vb
tasks, how to unwrap nested tasks
a0769dd2-0f6d-48ca-8418-a9d39de7f450

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