Task.RunSynchronously Method

Definition

Runs the Task synchronously on the current TaskScheduler.

Overloads

RunSynchronously(TaskScheduler)

Runs the Task synchronously on the TaskScheduler provided.

RunSynchronously()

Runs the Task synchronously on the current TaskScheduler.

RunSynchronously(TaskScheduler)

Runs the Task synchronously on the TaskScheduler provided.

public:
 void RunSynchronously(System::Threading::Tasks::TaskScheduler ^ scheduler);
public void RunSynchronously (System.Threading.Tasks.TaskScheduler scheduler);
member this.RunSynchronously : System.Threading.Tasks.TaskScheduler -> unit
Public Sub RunSynchronously (scheduler As TaskScheduler)

Parameters

scheduler
TaskScheduler

The scheduler on which to attempt to run this task inline.

Exceptions

The Task instance has been disposed.

The scheduler argument is null.

The Task is not in a valid state to be started. It may have already been started, executed, or canceled, or it may have been created in a manner that doesn't support direct scheduling.

Remarks

Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. The task to be run synchronously must be in the Created state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception.

If the target scheduler does not support running this task on the current thread, the task will be scheduled for execution on the scheduler, and the current thread will block until the task has completed execution. Because of this, the calling thread does not need to call a method such as Wait to ensure that the task has completed execution. For more information on exception handling for task operations, see Exception Handling.

See also

Applies to

RunSynchronously()

Runs the Task synchronously on the current TaskScheduler.

public:
 void RunSynchronously();
public void RunSynchronously ();
member this.RunSynchronously : unit -> unit
Public Sub RunSynchronously ()

Exceptions

The Task instance has been disposed.

The Task is not in a valid state to be started. It may have already been started, executed, or canceled, or it may have been created in a manner that doesn't support direct scheduling.

Examples

The following example compares a task executed by calling the RunSynchronously method with one executed asynchronously. In both cases, the tasks execute identical lambda expressions that display the task ID and the ID of the thread on which the task is running. The task calculates the sum of the integers between 1 and 1,000,000. As the output from the example shows, the task executed by calling the RunSynchronously method runs on the application thread, while the asynchronous task does not.

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

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application executing on thread {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var asyncTask = Task.Run( () => {  Console.WriteLine("Task {0} (asyncTask) executing on Thread {1}",
                                                           Task.CurrentId,
                                                           Thread.CurrentThread.ManagedThreadId);
                                         long sum = 0;
                                         for (int ctr = 1; ctr <= 1000000; ctr++ )
                                            sum += ctr;
                                         return sum;
                                      });
      var syncTask = new Task<long>( () =>  { Console.WriteLine("Task {0} (syncTask) executing on Thread {1}",
                                                                 Task.CurrentId,
                                                                 Thread.CurrentThread.ManagedThreadId);
                                              long sum = 0;
                                              for (int ctr = 1; ctr <= 1000000; ctr++ )
                                                 sum += ctr;
                                              return sum;
                                            });
      syncTask.RunSynchronously();
      Console.WriteLine();
      Console.WriteLine("Task {0} returned {1:N0}", syncTask.Id, syncTask.Result);
      Console.WriteLine("Task {0} returned {1:N0}", asyncTask.Id, asyncTask.Result);
   }
}
// The example displays the following output:
//       Application executing on thread 1
//       Task 1 (syncTask) executing on Thread 1
//       Task 2 (asyncTask) executing on Thread 3
//       1 status: RanToCompletion
//       2 status: RanToCompletion
//
//       Task 2 returned 500,000,500,000
//       Task 1 returned 500,000,500,000
open System
open System.Threading
open System.Threading.Tasks

printfn $"Application executing on thread {Thread.CurrentThread.ManagedThreadId}"

let asyncTask =
    Task.Run(fun () ->
        printfn $"Task {Task.CurrentId} (asyncTask) executing on Thread {Thread.CurrentThread.ManagedThreadId}"
        let mutable sum = 0L

        for i = 1 to 1000000 do
            sum <- sum + int64 i

        sum)

let syncTask =
    new Task<int64>(fun () ->
        printfn $"Task {Task.CurrentId} (syncTask) executing on Thread {Thread.CurrentThread.ManagedThreadId}"
        let mutable sum = 0L

        for i = 1 to 1000000 do
            sum <- sum + int64 i

        sum)

syncTask.RunSynchronously()
printfn $"\nTask {syncTask.Id} returned {syncTask.Result:N0}"
printfn $"Task {asyncTask.Id} returned {asyncTask.Result:N0}"

// The example displays the following output:
//       Application executing on thread 1
//       Task 1 (syncTask) executing on Thread 1
//       Task 2 (asyncTask) executing on Thread 3
//       1 status: RanToCompletion
//       2 status: RanToCompletion
//
//       Task 2 returned 500,000,500,000
//       Task 1 returned 500,000,500,000
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Console.WriteLine("Application executing on thread {0}",
                        Thread.CurrentThread.ManagedThreadId)
      Dim asyncTask = Task.Run( Function()
                                   Console.WriteLine("Task {0} (asyncTask) executing on Thread {1}",
                                                     Task.CurrentId,
                                                     Thread.CurrentThread.ManagedThreadId)
                                   Dim sum As Long = 0
                                   For ctr As Integer = 1 To 1000000
                                      sum += ctr
                                   Next
                                   Return sum
                                End Function)
      Dim syncTask As New Task(Of Long)( Function()
                                            Console.WriteLine("Task {0} (syncTask) executing on Thread {1}",
                                                              Task.CurrentId,
                                                              Thread.CurrentThread.ManagedThreadId)
                                            Dim sum As Long = 0
                                            For ctr As Integer = 1 To 1000000
                                               sum += ctr
                                            Next
                                            Return sum
                                         End Function)
      syncTask.RunSynchronously()
      Console.WriteLine()
      Console.WriteLine("Task {0} returned {1:N0}", syncTask.Id, syncTask.Result)
      Console.WriteLine("Task {0} returned {1:N0}", asyncTask.Id, asyncTask.Result)
   End Sub
End Module
' The example displays the following output:
'       Application executing on thread 1
'       Task 1 (syncTask) executing on Thread 1
'       Task 2 (asyncTask) executing on Thread 3
'       1 status: RanToCompletion
'       2 status: RanToCompletion
'
'       Task 2 returned 500,000,500,000
'       Task 1 returned 500,000,500,000

Remarks

Ordinarily, tasks are executed asynchronously on a thread pool thread and do not block the calling thread. Tasks executed by calling the RunSynchronously() method are associated with the current TaskScheduler and are run on the calling thread. If the target scheduler does not support running this task on the calling thread, the task will be scheduled for execution on the scheduler, and the calling thread will block until the task has completed execution. Even though the task runs synchronously, the calling thread should still call Wait to handle any exceptions that the task might throw. For more information on exception handling, see Exception Handling.

Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. The task to be run synchronously must be in the Created state. A task may be started and run only once. Any attempts to schedule a task a second time results in an exception.

See also

Applies to