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 運算式,以顯示工作識別碼和工作執行所在之執行緒的識別碼。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.

另請參閱

適用於