Export (0) Print
Expand All

How to: Chain Multiple Tasks with Continuations

In the Task Parallel Library, a task whose ContinueWith method is invoked is called the antecedent task and the task that is defined in the ContinueWith method is called the continuation. This example shows how to use the ContinueWith and ContinueWith methods of the Task and Task(Of TResult) classes to specify a task that starts after its antecedent task finishes.

The example also shows how to specify a continuation that runs only if its antecedent is canceled.

These examples demonstrate how to continue from a single task. You can also create a continuation that runs after any or all of a group of tasks complete or are canceled. For more information, see Task.WhenAll and Task.WhenAny.

The DoSimpleContinuation method shows the basic syntax for ContinueWith. Note that the antecedent task is provided as the input parameter to the lambda expression in the ContinueWith method. This enables you to evaluate the status of the antecedent task before it performs any work in the continuation. Use this simple overload of ContinueWith when you do not have to pass any state from one task to another.

The DoSimpleContinuationWithState method shows how to use ContinueWith to pass the result from the antecedent task to the continuation task.

Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Module ContinueWith

    Sub Main()
        DoSimpleContinuation()

        Console.WriteLine("Press any key to exit")
        Console.ReadKey()
    End Sub 


    Sub DoSimpleContinuation()
        Dim path As String = "C:\users\public\TPLTestFolder\" 
        Try 
            Dim firstTask = New Task(Sub() CopyDataIntoTempFolder(path))
            Dim secondTask = firstTask.ContinueWith(Sub(t) CreateSummaryFile(path))
            firstTask.Start()
        Catch e As AggregateException
            Console.WriteLine(e.Message)
        End Try 
    End Sub 

    ' A toy function to simulate a workload 
    Sub CopyDataIntoTempFolder(ByVal path__1 As String)
        System.IO.Directory.CreateDirectory(path__1)
        Dim rand As New Random()
        For x As Integer = 0 To 49
            Dim bytes As Byte() = New Byte(999) {}
            rand.NextBytes(bytes)
            Dim filename As String = Path.GetRandomFileName()
            Dim filepath As String = Path.Combine(path__1, filename)
            System.IO.File.WriteAllBytes(filepath, bytes)
        Next 
    End Sub 

    Sub CreateSummaryFile(ByVal path__1 As String)
        Dim files As String() = System.IO.Directory.GetFiles(path__1)
        Parallel.ForEach(files, Sub(file)
                                    Thread.SpinWait(5000)
                                End Sub)

        System.IO.File.WriteAllText(Path.Combine(path__1, "__SummaryFile.txt"), "did my work")
        Console.WriteLine("Done with task2")
    End Sub 

    Sub DoSimpleContinuationWithState()
        Dim nums As Integer() = {19, 17, 21, 4, 13, 8, _
        12, 7, 3, 5}
        Dim f0 = New Task(Of Double)(Function() nums.Average())
        Dim f1 = f0.ContinueWith(Function(t) GetStandardDeviation(nums, t.Result))

        f0.Start()
        Console.WriteLine("the standard deviation is {0}", f1)
    End Sub 

    Function GetStandardDeviation(ByVal values As Integer(), ByVal mean As Double) As Double 
        Dim d As Double = 0.0R
        For Each n In values
            d += Math.Pow(mean - n, 2)
        Next 
        Return Math.Sqrt(d / (values.Length - 1))
    End Function 
End Module

The type parameter of the Task(Of TResult) determines the return type of the delegate. That return value is passed to the continuation task. An arbitrary number of tasks can be chained in this manner.

Show:
© 2014 Microsoft