Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

Task.ContinueWith(Of TResult) Method (Func(Of Task, TResult), CancellationToken, TaskContinuationOptions, TaskScheduler)

Creates a continuation that executes according to the condition specified in continuationOptions.

Namespace:  System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)
'Declaration
Public Function ContinueWith(Of TResult) ( _
	continuationFunction As Func(Of Task, TResult), _
	cancellationToken As CancellationToken, _
	continuationOptions As TaskContinuationOptions, _
	scheduler As TaskScheduler _
) As Task(Of TResult)

Type Parameters

TResult

The type of the result produced by the continuation.

Parameters

continuationFunction
Type: System.Func(Of Task, TResult)
A function to run according to the specified continuationOptions. When run, the delegate will be passed the completed task as an argument.
cancellationToken
Type: System.Threading.CancellationToken
The CancellationToken that will be assigned to the new continuation task.
continuationOptions
Type: System.Threading.Tasks.TaskContinuationOptions
Options for when the continuation is scheduled and how it behaves. This includes criteria, such as OnlyOnCanceled, as well as execution options, such as ExecuteSynchronously.
scheduler
Type: System.Threading.Tasks.TaskScheduler
The TaskScheduler to associate with the continuation task and to use for its execution.

Return Value

Type: System.Threading.Tasks.Task(Of TResult)
A new continuation Task(Of TResult).
ExceptionCondition
ObjectDisposedException

The Task has been disposed.

-or-

The CancellationTokenSource that created the token has already been disposed.

ArgumentNullException

The continuationFunction argument is Nothing.

-or-

The scheduler argument is Nothing.

ArgumentOutOfRangeException

The continuationOptions argument specifies an invalid value for TaskContinuationOptions.

The returned Task(Of TResult) will not be scheduled for execution until the current task has completed. If the criteria specified through the continuationOptions parameter are not met, the continuation task will be canceled instead of scheduled.

The following example shows how to use the ContinueWith method with continuation options:


Imports System.Threading
Imports System.Threading.Tasks
Module ContuationOptionsDemo
    ' Demonstrated features:
    '   TaskContinuationOptions
    '   Task.ContinueWith()
    '   Task.Factory
    '   Task.Wait()
    ' Expected results:
    '   This sample demonstrates branched continuation sequences - Task+Commit or Task+Rollback.
    '   Notice that no if statements are used.
    '   The first sequence is successful - tran1 and commitTran1 are executed. rollbackTran1 is canceled.
    '   The second sequence is unsuccessful - tran2 and rollbackTran2 are executed. tran2 is faulted, and commitTran2 is canceled.
    ' Documentation:
    '   http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions(VS.100).aspx
    Private Sub Main()
        Dim success As Action = Sub()
                                    Console.WriteLine("Task={0}, Thread={1}: Begin successful transaction", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                End Sub

        Dim failure As Action = Sub()
                                    Console.WriteLine("Task={0}, Thread={1}: Begin transaction and encounter an error", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                    Throw New InvalidOperationException("SIMULATED EXCEPTION")
                                End Sub

        Dim commit As Action(Of Task) = Sub(antecendent)
                                            Console.WriteLine("Task={0}, Thread={1}: Commit transaction", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                        End Sub

        Dim rollback As Action(Of Task) = Sub(antecendent)
                                              ' "Observe" your antecedent's exception so as to avoid an exception
                                              ' being thrown on the finalizer thread
                                              Dim unused = antecendent.Exception

                                              Console.WriteLine("Task={0}, Thread={1}: Rollback transaction", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                          End Sub

        ' Successful transaction - Begin + Commit
        Console.WriteLine("Demonstrating a successful transaction")

        ' Initial task
        ' Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
        Dim tran1 As Task = Task.Factory.StartNew(success)

        ' The following task gets scheduled only if tran1 completes successfully
        Dim commitTran1 = tran1.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion)

        ' The following task gets scheduled only if tran1 DOES NOT complete successfully
        Dim rollbackTran1 = tran1.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion)

        ' For demo purposes, wait for the sample to complete
        commitTran1.Wait()

        ' -----------------------------------------------------------------------------------


        ' Failed transaction - Begin + exception + Rollback 
        Console.WriteLine(vbLf & "Demonstrating a failed transaction")

        ' Initial task
        ' Treated as "fire-and-forget" -- any exceptions will be cleaned up in rollback continuation
        Dim tran2 As Task = Task.Factory.StartNew(failure)

        ' The following task gets scheduled only if tran2 completes successfully
        Dim commitTran2 = tran2.ContinueWith(commit, TaskContinuationOptions.OnlyOnRanToCompletion)

        ' The following task gets scheduled only if tran2 DOES NOT complete successfully
        Dim rollbackTran2 = tran2.ContinueWith(rollback, TaskContinuationOptions.NotOnRanToCompletion)

        ' For demo purposes, wait for the sample to complete
        rollbackTran2.Wait()
    End Sub
End Module



Imports System.Threading
Imports System.Threading.Tasks

Module ContinuationWhenMulti
    ' Demonstrated features:
    '   Task.Factory
    '   TaskFactory.ContinueWhenAll()
    '   TaskFactory.ContinueWhenAny()
    '   Task.Wait()
    ' Expected results:
    '   Three tasks are created in parallel. 
    '   Each task for a different period of time prints a number and returns it.
    '   A ContinueWhenAny() task indicates the first of the three tasks to complete.
    '   A ContinueWhenAll() task sums up the results of the three tasks and prints out the total.
    ' Documentation:
    '   http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory_members(VS.100).aspx
    Sub Main()
        ' Schedule a list of tasks that return integer
        Dim tasks As Task(Of Integer)() = New Task(Of Integer)() {
            Task(Of Integer).Factory.StartNew(Function()
                                                  Thread.Sleep(500)
                                                  Console.WriteLine("Task={0}, Thread={1}, x=5", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                                  Return 5
                                              End Function),
            Task(Of Integer).Factory.StartNew(Function()
                                                  Thread.Sleep(10)
                                                  Console.WriteLine("Task={0}, Thread={1}, x=3", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                                  Return 3
                                              End Function),
            Task(Of Integer).Factory.StartNew(Function()
                                                  Thread.Sleep(200)
                                                  Console.WriteLine("Task={0}, Thread={1}, x=2", Task.CurrentId, Thread.CurrentThread.ManagedThreadId)
                                                  Return 2
                                              End Function)}


        ' Schedule a continuation to indicate the result of the first task to complete
        Task.Factory.ContinueWhenAny(tasks, Sub(winner)
                                                ' You would expect winning result = 3 on multi-core systems, because you expect
                                                ' tasks[1] to finish first.
                                                Console.WriteLine("Task={0}, Thread={1} (ContinueWhenAny): Winning result = {2}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId, winner.Result)
                                            End Sub)


        ' Schedule a continuation that sums up the results of all tasks, then wait on it.
        ' The list of antecendent tasks is passed as an argument by the runtime.
        Task.Factory.ContinueWhenAll(tasks, Sub(antecendents)
                                                Dim sum As Integer = 0
                                                For Each task__1 As Task(Of Integer) In antecendents
                                                    sum += task__1.Result
                                                Next
                                                Console.WriteLine("Task={0}, Thread={1}, (ContinueWhenAll): Total={2} (expected 10)", Task.CurrentId, Thread.CurrentThread.ManagedThreadId, sum)
                                            End Sub).Wait()
    End Sub


End Module


.NET Framework

Supported in: 4

.NET Framework Client Profile

Supported in: 4

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.