Task.RunSynchronously 方法

定义

对当前的 Task 同步运行 TaskSchedulerRuns the Task synchronously on the current TaskScheduler.

重载

RunSynchronously()

对当前的 Task 同步运行 TaskSchedulerRuns the Task synchronously on the current TaskScheduler.

RunSynchronously(TaskScheduler)

对提供的 Task 同步运行 TaskSchedulerRuns the Task synchronously on the TaskScheduler provided.

RunSynchronously()

对当前的 Task 同步运行 TaskSchedulerRuns the Task synchronously on the current TaskScheduler.

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

异常

已释放了 Task 实例。The Task instance has been disposed.

Task 并非要启动的有效状态。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.

示例

下面的示例将通过调用 RunSynchronously 方法执行的任务与异步执行的任务进行比较。The following example compares a task executed by calling the RunSynchronously method with one executed asynchronously. 在这两种情况下,任务执行相同的 lambda 表达式,用于显示任务 ID 以及运行任务的线程的 ID。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. 该任务计算1到1000000之间的整数之和。The task calculates the sum of the integers between 1 and 1,000,000. 如示例的输出所示,通过调用 RunSynchronously 方法执行的任务在应用程序线程上运行,而异步任务则不运行。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
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

注解

通常,任务在线程池线程上以异步方式执行,并且不会阻止调用线程。Ordinarily, tasks are executed asynchronously on a thread pool thread and do not block the calling thread. 通过调用 RunSynchronously() 方法执行的任务与当前 TaskScheduler 相关联,并在调用线程上运行。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. 即使任务以同步方式运行,调用线程仍应调用 Wait 以处理任务可能引发的任何异常。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.

通过调用 RunSynchronously 方法执行的任务通过调用 TaskTask<TResult> 类构造函数进行实例化。Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. 要同步运行的任务必须处于 Created 状态。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.

另请参阅

RunSynchronously(TaskScheduler)

对提供的 Task 同步运行 TaskSchedulerRuns 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)

参数

scheduler
TaskScheduler

尝试对其以内联方式运行此任务的计划程序。The scheduler on which to attempt to run this task inline.

异常

已释放了 Task 实例。The Task instance has been disposed.

scheduler 参数为 nullThe scheduler argument is null.

Task 并非要启动的有效状态。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.

注解

通过调用 RunSynchronously 方法执行的任务通过调用 TaskTask<TResult> 类构造函数进行实例化。Tasks executed by calling the RunSynchronously method are instantiated by calling a Task or Task<TResult> class constructor. 要同步运行的任务必须处于 Created 状态。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. 因此,调用线程不需要调用方法(如 Wait)来确保任务已完成执行。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.

另请参阅

适用于