Export (0) Print
Expand All

TaskExtensions.Unwrap Method (Task<Task>)

Creates a proxy Task that represents the asynchronous operation of a TryExecuteTaskInline.

Namespace:  System.Threading.Tasks
Assembly:  System.Core (in System.Core.dll)

public static Task Unwrap(
	this Task<Task> task
)

Parameters

task
Type: System.Threading.Tasks.Task<Task>

The Task<Task> (C#) or Task (Of Task) (Visual Basic) to unwrap.

Return Value

Type: System.Threading.Tasks.Task
A Task that represents the asynchronous operation of the provided System.Threading.Tasks.Task(Of Task).

Usage Note

In Visual Basic and C#, you can call this method as an instance method on any object of type Task<Task>. When you use instance method syntax to call this method, omit the first parameter. For more information, see Extension Methods (Visual Basic) or Extension Methods (C# Programming Guide).

ExceptionCondition
ArgumentNullException

The exception that is thrown if the task argument is null.

It is often useful to be able to return a Task from a Task<TResult>, where the inner Task represents work done as part of the outer Task<TResult>. However, doing so results in a Task<Task> (C#) or Task (Of Task) (Visual Basic), which, if not dealt with carefully, could produce unexpected behavior. Unwrap solves this problem by creating a proxy Task that represents the entire asynchronous operation of such a task.

The following example shows how to unwrap a task:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

class UnWrapDemo
{
     // Demonstrated features: 
        //		Task.Unwrap() 
        // 		Task.Factory.StartNew() 
        //		Task.ContinueWith() 
        // Expected results: 
        // 		Indicates that continuation chains can be set up virtually instantaneously using Unwrap(), and then left to run on their own. 
        //      The results of the RemoteIncrement(0) chain and the RemoteIncrement(4) chain may be intermixed with each other. 
        //		The results of the sequence that starts with RemoteIncrement(4) are in strict order. 
        // Documentation: 
        //		http://msdn.microsoft.com/en-us/library/dd781129(VS.100).aspx 
        // More information: 
        //		http://blogs.msdn.com/pfxteam/archive/2009/11/04/9917581.aspx 
        // Other notes: 
        //		The combination of Task<T>, ContinueWith() and Unwrap() can be particularly useful for setting up a chain of long-running 
        //      tasks where each task uses the results of its predecessor. 
        static void Main()
        {
            // Invoking individual tasks is straightforward
            Task<int> t1 = RemoteIncrement(0);
            Console.WriteLine("Started RemoteIncrement(0)");

            // Chain together the results of (simulated) remote operations. 
            // The use of Unwrap() instead of .Result below prevents this thread from blocking while setting up this continuation chain.
            Task<int> t2 = RemoteIncrement(4)
                .ContinueWith(t => RemoteIncrement(t.Result))			// RemoteIncrement() returns Task<int> so no unwrapping is needed for the first continuation.
                .Unwrap().ContinueWith(t => RemoteIncrement(t.Result))	// ContinueWith() returns Task<Task<int>>. Therefore unwrapping is needed.
                .Unwrap().ContinueWith(t => RemoteIncrement(t.Result))	// and on it goes...
                .Unwrap();
            Console.WriteLine("Started RemoteIncrement(...(RemoteIncrement(RemoteIncrement(4))...)");

            try
            {
                t1.Wait();
                Console.WriteLine("Finished RemoteIncrement(0)\n");

                t2.Wait();
                Console.WriteLine("Finished RemoteIncrement(...(RemoteIncrement(RemoteIncrement(4))...)");
            }
            catch (AggregateException e)
            {
                Console.WriteLine("A task has thrown the following (unexpected) exception:\n{0}", e);
            }

        }
        // This method represents a remote API. 
        static Task<int> RemoteIncrement(int n)
        {
            return Task<int>.Factory.StartNew(
                (obj) =>
                {
                    // Simulate a slow operation
                    Thread.Sleep(1 * 1000);

                    int x = (int)obj;
                    Console.WriteLine("Thread={0}, Next={1}", Thread.CurrentThread.ManagedThreadId, ++x);
                    return x;
                },
                n);
        }

}

.NET Framework

Supported in: 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft