TaskFactory.StartNew 方法

定義

建立並啟動 TaskCreates and starts a Task.

多載

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 TaskCreates and starts a Task.

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 TaskCreates and starts a Task.

StartNew(Action<Object>, Object, TaskCreationOptions)

建立並啟動 TaskCreates and starts a Task.

StartNew(Action<Object>, Object, CancellationToken)

建立並啟動 TaskCreates and starts a Task.

StartNew(Action, CancellationToken)

建立並啟動 TaskCreates and starts a Task.

StartNew(Action, TaskCreationOptions)

建立並啟動 TaskCreates and starts a Task.

StartNew(Action)

建立並啟動工作。Creates and starts a task.

StartNew(Action<Object>, Object)

建立並啟動 TaskCreates and starts a Task.

StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<TResult>)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<TResult>, CancellationToken)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<TResult>, TaskCreationOptions)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

備註

.NET Framework 4.5.NET Framework 4.5 開始,@no__t 1 方法是啟動計算系結工作的建議方式。Starting with the .NET Framework 4.5.NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. 只有當您需要精細控制長時間執行的計算系結工作時,才使用 StartNew 方法。Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task. 這包括您想要控制下列各項的案例:This includes scenarios in which you want to control the following:

  • 工作建立選項。Task creation options. 預設會使用 TaskCreationOptions.DenyChildAttach 選項來建立 Task.Run 方法所建立的工作。Tasks created by the Task.Run method by default are created with the TaskCreationOptions.DenyChildAttach option. 若要覆寫此行為,或提供其他 TaskCreationOptions 選項,請呼叫 @no__t 1 多載。To override this behavior, or to provide other TaskCreationOptions options, call a StartNew overload.

  • 參數傳遞。Parameter passing. @No__t (0)方法的多載不允許您將參數傳遞給工作委派。The overloads of the Task.Run method do not allow you to pass a parameter to the task delegate. @No__t-0 方法的多載。Overloads of the StartNew method do.

  • 工作排程器。The task scheduler. @No__t (0)方法的多載會使用預設工作排程器。The overloads of the Task.Run method use the default task scheduler. 若要控制工作排程器,請使用 scheduler 參數來呼叫 @no__t 0 多載。To control the task scheduler, call a StartNew overload with a scheduler parameter. 如需詳細資訊,請參閱TaskSchedulerFor more information, see TaskScheduler.

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Action<obj> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task

參數

action
Action<Object>

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

state
Object

物件,包含 action 委派要使用的資料。An object containing data to be used by the action delegate.

cancellationToken
CancellationToken

要指派給新工作的 CancellationTokenThe CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制已建立之 Task 的行為。A TaskCreationOptions value that controls the behavior of the created Task

scheduler
TaskScheduler

TaskScheduler,用來排定建立的接續 TaskThe TaskScheduler that is used to schedule the created Task.

傳回

啟動的 TaskThe started Task.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

actionnullaction is null.

-或--or-

schedulernullscheduler is null.

creationOptions 引數指定無效的 TaskCreationOptions 值。creationOptions argument specifies an invalid TaskCreationOptions value. 如需詳細資訊,請參閱 FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions) 的<備註>For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task StartNew (Action action, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Action * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task

參數

action
Action

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

cancellationToken
CancellationToken

CancellationToken,將指派給新的 TaskThe CancellationToken that will be assigned to the new Task

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制下列已建立之項目的行為:TaskA TaskCreationOptions value that controls the behavior of the created Task

scheduler
TaskScheduler

TaskScheduler,用來排定建立的接續 TaskThe TaskScheduler that is used to schedule the created Task.

傳回

啟動的 TaskThe started Task.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

actionnullaction is null.

-或--or- schedulernullscheduler is null.

creationOptions 指定無效的 TaskCreationOptions 值。creationOptions specifies an invalid TaskCreationOptions value. 如需詳細資訊,請參閱 FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions) 的<備註>For more information, see the Remarks for FromAsync(Func<AsyncCallback,Object,IAsyncResult>, Action<IAsyncResult>, Object, TaskCreationOptions)

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action<Object>, Object, TaskCreationOptions)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Action<obj> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Function StartNew (action As Action(Of Object), state As Object, creationOptions As TaskCreationOptions) As Task

參數

action
Action<Object>

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

state
Object

物件,包含 action 委派要使用的資料。An object containing data to be used by the action delegate.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制下列已建立之項目的行為:TaskA TaskCreationOptions value that controls the behavior of the created Task

傳回

啟動的 TaskThe started Task.

例外狀況

actionnullaction is null.

creationOptions 指定無效的 TaskCreationOptions 值。creationOptions specifies an invalid TaskCreationOptions value.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action<Object>, Object, CancellationToken)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Action<obj> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task

參數

action
Action<Object>

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

state
Object

物件,包含 action 委派要使用的資料。An object containing data to be used by the action delegate.

cancellationToken
CancellationToken

CancellationToken,將指派給新的 TaskThe CancellationToken that will be assigned to the new Task

傳回

啟動的 TaskThe started Task.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

actionnullaction is null.

範例

下列範例會定義6個字母的單字陣列。The following example defines an array of 6-letter words. 接著會將每個字組傳遞至 @no__t 0 的委派,這會將此單字混雜成,並顯示原始字組和其已打亂的版本。Each word is then passed to an Action<T> delegate, which scrambles the word and displays the original word and its scrambled version.

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      CancellationTokenSource cts = new CancellationTokenSource();
      CancellationToken token = cts.Token;
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      token.ThrowIfCancellationRequested();
                                                      bool wasZero = false;
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++) {
                                                             order[ctr] = rnd.NextDouble();
                                                             if (order[ctr] == 0) {
                                                                if (! wasZero) {
                                                                   wasZero = true;
                                                                }
                                                                else {
                                                                   cts.Cancel();
                                                                }
                                                             }
                                                         }
                                                      }
                                                      token.ThrowIfCancellationRequested();
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6, token));

      try {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException e) {
         foreach (var ie in e.InnerExceptions) {
            if (ie is OperationCanceledException) {
               Console.WriteLine("The word scrambling operation has been cancelled.");
               break;
            }
            else {
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message);
            }
         }
      }
      finally {
         cts.Dispose();
      }
   }
}
// The example displays output like the following:
//    regain --> irnaeg
//    ordain --> rioadn
//    reason --> soearn
//    rained --> rinade
//    rioter --> itrore
//    senior --> norise
//    rental --> atnerl
//    editor --> oteird
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim cts As New CancellationTokenSource()
      Dim token As CancellationToken = cts.Token
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         tasks.Add(Task.Factory.StartNew( Sub(word)
                                              Dim chars() As Char = word.ToString().ToCharArray()
                                              Dim order(chars.Length - 1) As Double
                                              Dim wasZero As Boolean = False
                                              SyncLock lockObj
                                                 For ctr As Integer = 0 To order.Length - 1
                                                    order(ctr) = rnd.NextDouble()
                                                    If order(ctr) = 0 Then
                                                       If Not wasZero Then
                                                          wasZero = True
                                                       Else
                                                          cts.Cancel()
                                                       End If
                                                    End If
                                                 Next
                                              End SyncLock
                                              token.ThrowIfCancellationRequested()
                                              Array.Sort(order, chars)
                                              Console.WriteLine("{0} --> {1}", word,
                                                                new String(chars))
                                          End Sub, word6))
      Next
      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         For Each ie In e.InnerExceptions
            If TypeOf ie Is OperationCanceledException
               Console.WriteLine("The word scrambling operation has been cancelled.")
               Exit For
            Else
               Console.WriteLine(ie.GetType().Name + ": " + ie.Message)
            End If
         Next
      Finally
         cts.Dispose()
      End Try
   End Sub
End Module
' The example displays output like the following:
'       regain --> irnaeg
'       ordain --> rioadn
'       reason --> soearn
'       rained --> rinade
'       rioter --> itrore
'       senior --> norise
'       rental --> atnerl
'       editor --> oteird

請注意,此範例會初始化單一亂數產生器,此產生器受到鎖定保護。Note that the example initializes a single random number generator, which is protected by a lock. 如需鎖定的需求,請參閱 Random 類別主題中的「系統隨機類別和執行緒安全性」。For the need of a lock, see "The System.Random class and thread safety" in the Random class topic. 為了處理亂數字產生器的損毀可能性,會將解除標記傳遞給工作。To handle the possibility of corruption of the random number generator, a cancellation token is passed to task. 如果兩個亂數字等於零,此方法會假設亂數產生器已損毀,並設定解除標記。If two random numbers equal zero, the method assumes that the random number generator is corrupted and sets the cancellation token. 在排序包含單字中六個字元的 chars 陣列之前,如果已解除標記,方法會呼叫 CancellationToken.ThrowIfCancellationRequested 方法來擲回 OperationCanceledExceptionBefore sorting the chars array that contains the six characters in a word, the method calls the CancellationToken.ThrowIfCancellationRequested method to throw an OperationCanceledException if the token has been canceled.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action, CancellationToken)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task StartNew (Action action, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task

參數

action
Action

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

cancellationToken
CancellationToken

要指派給新工作的 CancellationTokenThe CancellationToken that will be assigned to the new task.

傳回

啟動的 TaskThe started Task.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

actionnullaction is null.

範例

下列範例會呼叫 StartNew(Action, CancellationToken) 方法,以建立可逐一查看 C:\Windows\System32 目錄中檔案的工作。The following example calls the StartNew(Action, CancellationToken) method to create a task that iterates the files in the C:\Windows\System32 directory. Lambda 運算式會呼叫 Parallel.ForEach 方法,將每個檔案的相關資訊加入至 @no__t 1 物件。The lambda expression calls the Parallel.ForEach method to add information about each file to a List<T> object. @No__t-0 迴圈所叫用的每個已卸離的嵌套工作都會檢查解除標記的狀態,而且如果要求取消,則會呼叫 CancellationToken.ThrowIfCancellationRequested 方法。Each detached nested task invoked by the Parallel.ForEach loop checks the state of the cancellation token and, if cancellation is requested, calls the CancellationToken.ThrowIfCancellationRequested method. 當呼叫端執行緒呼叫 Task.Wait 方法時,CancellationToken.ThrowIfCancellationRequested 方法會擲回在 @no__t 2 區塊中處理的 OperationCanceledException 例外狀況。The CancellationToken.ThrowIfCancellationRequested method throws an OperationCanceledException exception that is handled in a catch block when the calling thread calls the Task.Wait method.

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Factory.StartNew( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        , token);
      tokenSource.Cancel();
      try {
         t.Wait(); 
         Console.WriteLine("Retrieved information for {0} files.", files.Count);
      }
      catch (AggregateException e) {
         Console.WriteLine("Exception messages:");
         foreach (var ie in e.InnerExceptions)
            Console.WriteLine("   {0}: {1}", ie.GetType().Name, ie.Message);

         Console.WriteLine("\nTask status: {0}", t.Status);       
      }
      finally {
         tokenSource.Dispose();
      }
   }
}
// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//       
//       Task status: Canceled
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tokenSource As New CancellationTokenSource()
      Dim token As CancellationToken = tokenSource.Token
      Dim files As New List(Of Tuple(Of String, String, Long, Date))()

      Dim t As Task = Task.Factory.StartNew( Sub()
                                   Dim dir As String = "C:\Windows\System32\"
                                   Dim obj As New Object()
                                   If Directory.Exists(dir)Then
                                      Parallel.ForEach(Directory.GetFiles(dir), 
                                         Sub(f)
                                            If token.IsCancellationRequested Then
                                               token.ThrowIfCancellationRequested()
                                            End If  
                                            Dim fi As New FileInfo(f)
                                            SyncLock(obj)
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc))          
                                            End SyncLock
                                         End Sub)
                                   End If
                                End Sub, token)
      tokenSource.Cancel()
      Try
         t.Wait() 
         Console.WriteLine("Retrieved information for {0} files.", files.Count)
      Catch e As AggregateException
         Console.WriteLine("Exception messages:")
         For Each ie As Exception In e.InnerExceptions
            Console.WriteLine("   {0}:{1}", ie.GetType().Name, ie.Message)
         Next
         Console.WriteLine()
         Console.WriteLine("Task status: {0}", t.Status)       
      Finally
         tokenSource.Dispose()
      End Try
   End Sub
End Module
' The example displays the following output:
'       Exception messages:
'          TaskCanceledException: A task was canceled.
'       
'       Task status: Canceled

備註

呼叫 StartNew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以使用 Task.Run(Action, CancellationToken) 方法來快速地呼叫 StartNew(Action, CancellationToken) 與預設參數。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Task.Run(Action, CancellationToken) method as a quick way to call StartNew(Action, CancellationToken) with default parameters. 不過,請注意,與 @no__t 有關的兩個方法之間的行為差異,預設不允許以 TaskCreationOptions.AttachedToParent 選項啟動的子工作附加至目前的 Task 實例,而 StartNew(Action, CancellationToken) 則會執行此作業。Note, however, that there is a difference in behavior between the two methods regarding : Task.Run(Action, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task instance, whereas StartNew(Action, CancellationToken) does. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action, TaskCreationOptions)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task StartNew (Action action, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Action * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task

參數

action
Action

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制下列已建立之項目的行為:TaskA TaskCreationOptions value that controls the behavior of the created Task

傳回

啟動的 TaskThe started Task.

例外狀況

actionnullaction is null.

creationOptions 指定無效的 TaskCreationOptions 值。creationOptions specifies an invalid TaskCreationOptions value.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action)

建立並啟動工作。Creates and starts a task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action ^ action);
public System.Threading.Tasks.Task StartNew (Action action);
member this.StartNew : Action -> System.Threading.Tasks.Task

參數

action
Action

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

傳回

已開始的工作。The started task.

例外狀況

action 引數為 nullThe action argument is null.

範例

下列範例會使用 StartNew(Action) 方法來重複叫用產生亂數的 @no__t 1 委派,將它解釋為 Unicode 程式碼點,將它轉換成 UTF16 編碼的程式碼單位,並顯示產生之字元的相關資訊,或長度.The following example uses the StartNew(Action) method to repeatedly invoke an Action delegate that generates a random number, interprets it as a Unicode code point, converts it to a UTF16-encoded code unit, and displays information about the resulting character or characters.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      List<Task> tasks  = new List<Task>();
      // Execute the task 10 times.
      for (int ctr = 1; ctr <= 9; ctr++) {
         tasks.Add(Task.Factory.StartNew( () => {
                                            int utf32 = 0;
                                            lock(rnd) {
                                               // Get UTF32 value.
                                               utf32 = rnd.Next(0, 0xE01F0);
                                            }
                                            // Convert it to a UTF16-encoded character.
                                            string utf16 = Char.ConvertFromUtf32(utf32);
                                            // Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16));
                                         }));                           
      }
      Task.WaitAll(tasks.ToArray()); 
   }

   private static string ShowHex(string value)
   {
      string hexString = null;
      // Handle only non-control characters.
      if (! Char.IsControl(value, 0)) {
         foreach (var ch in value)
            hexString += String.Format("0x{0} ", Convert.ToUInt16(ch));

      }   
      return hexString.Trim();
   }
}
// The example displays the following output:
//       0x00097103 --> '򗄃' (0x55836 0x56579)
//       0x000A98A1 --> '򩢡' (0x55910 0x56481)
//       0x00050002 --> '񐀂' (0x55552 0x56322)
//       0x0000FEF1 --> 'ﻱ' (0x65265)
//       0x0008BC0A --> '򋰊' (0x55791 0x56330)
//       0x000860EA --> '򆃪' (0x55768 0x56554)
//       0x0009AC5A --> '򚱚' (0x55851 0x56410)
//       0x00053320 --> '񓌠' (0x55564 0x57120)
//       0x000874EF --> '򇓯' (0x55773 0x56559)
Imports System.Collections.Generic
Imports System.Threading.Tasks

Public Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task)
      ' Execute the task 10 times.
      For ctr As Integer = 1 To 9
         tasks.Add(Task.Factory.StartNew(Sub()
                                            Dim utf32 As Integer
                                            SyncLock(rnd)
                                               ' Get UTF32 value.
                                               utf32 = rnd.Next(0, &hE01F0)
                                            End SyncLock
                                            ' Convert it to a UTF16-encoded character.
                                            Dim utf16 As String = Char.ConvertFromUtf32(utf32)
                                            ' Display information about the character.
                                            Console.WriteLine("0x{0:X8} --> '{1,2}' ({2})", 
                                                              utf32, utf16, ShowHex(utf16))
                                         End Sub))                           
      Next
      Task.WaitAll(tasks.ToArray()) 
   End Sub
   
   Private Function ShowHex(value As String) As String
      Dim hexString As String = Nothing
      ' Handle only non-control characters.
      If Not Char.IsControl(value, 0) Then
         For Each ch In value
            hexString += String.Format("0x{0} ", Convert.ToUInt16(ch))
         Next
      End If   
      Return hexString.Trim()
   End Function
End Module
' The example displays output similar to the following:
'       0x00097103 --> '򗄃' (0x55836 0x56579)
'       0x000A98A1 --> '򩢡' (0x55910 0x56481)
'       0x00050002 --> '񐀂' (0x55552 0x56322)
'       0x0000FEF1 --> 'ﻱ' (0x65265)
'       0x0008BC0A --> '򋰊' (0x55791 0x56330)
'       0x000860EA --> '򆃪' (0x55768 0x56554)
'       0x0009AC5A --> '򚱚' (0x55851 0x56410)
'       0x00053320 --> '񓌠' (0x55564 0x57120)
'       0x000874EF --> '򇓯' (0x55773 0x56559)

備註

呼叫 StartNew 在功能上相當於使用其中一個函式來建立工作,然後呼叫 @no__t 1 方法來排程執行工作。Calling StartNew is functionally equivalent to creating a task by using one of its constructors, and then calling the Task.Start method to schedule the task for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以使用 Task.Run(Action) 方法來快速地呼叫 StartNew(Action) 與預設參數。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Task.Run(Action) method as a quick way to call StartNew(Action) with default parameters. 不過,請注意,與 @no__t 有關的兩個方法之間的行為差異,預設不允許以 TaskCreationOptions.AttachedToParent 選項啟動的子工作附加至目前的 Task 實例,而 StartNew(Action) 則會執行此作業。Note, however, that there is a difference in behavior between the two methods regarding : Task.Run(Action) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task instance, whereas StartNew(Action) does. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew(Action<Object>, Object)

建立並啟動 TaskCreates and starts a Task.

public:
 System::Threading::Tasks::Task ^ StartNew(Action<System::Object ^> ^ action, System::Object ^ state);
public System.Threading.Tasks.Task StartNew (Action<object> action, object state);
member this.StartNew : Action<obj> * obj -> System.Threading.Tasks.Task
Public Function StartNew (action As Action(Of Object), state As Object) As Task

參數

action
Action<Object>

要以非同步方式執行的動作委派。The action delegate to execute asynchronously.

state
Object

物件,包含 action 委派要使用的資料。An object containing data to be used by the action delegate.

傳回

啟動的 TaskThe started Task.

例外狀況

action 引數為 nullThe action argument is null.

範例

下列範例會定義6個字母的單字陣列。The following example defines an array of 6-letter words. 接著會將每個字組傳遞至 @no__t 0 的委派,這會將此單字混雜成,並顯示原始字組和其已打亂的版本。Each word is then passed to an Action<T> delegate, which scrambles the word and displays the original word and its scrambled version.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task>();
      Random rnd = new Random();
      Object lockObj = new Object();
      String[] words6 = { "reason", "editor", "rioter", "rental",
                          "senior", "regain", "ordain", "rained" };

      foreach (var word6 in words6)
         tasks.Add(Task.Factory.StartNew( (word) => { Char[] chars = word.ToString().ToCharArray();
                                                      double[] order = new double[chars.Length];
                                                      lock (lockObj) {
                                                         for (int ctr = 0; ctr < order.Length; ctr++)
                                                             order[ctr] = rnd.NextDouble();
                                                      }
                                                      Array.Sort(order, chars);
                                                      Console.WriteLine("{0} --> {1}", word,
                                                                        new String(chars));
                                                    }, word6));

      Task.WaitAll(tasks.ToArray());
   }
}
// The example displays output like the following:
//    regain --> irnaeg
//    ordain --> rioadn
//    reason --> soearn
//    rained --> rinade
//    rioter --> itrore
//    senior --> norise
//    rental --> atnerl
//    editor --> oteird
Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         tasks.Add(Task.Factory.StartNew( Sub(word)
                                              Dim chars() As Char = word.ToString().ToCharArray()
                                              Dim order(chars.Length - 1) As Double
                                              SyncLock lockObj
                                                 For ctr As Integer = 0 To order.Length - 1
                                                    order(ctr) = rnd.NextDouble()
                                                 Next
                                              End SyncLock
                                              Array.Sort(order, chars)
                                              Console.WriteLine("{0} --> {1}", word,
                                                                new String(chars))
                                          End Sub, word6))
      Next
      Task.WaitAll(tasks.ToArray())
   End Sub
End Module
' The example displays output like the following:
'       regain --> irnaeg
'       ordain --> rioadn
'       reason --> soearn
'       rained --> rinade
'       rioter --> itrore
'       senior --> norise
'       rental --> atnerl
'       editor --> oteird

請注意,此範例會初始化單一亂數產生器,此產生器受到鎖定保護。Note that the example initializes a single random number generator, which is protected by a lock. 如需鎖定的需求,請參閱 Random 類別主題中的「系統隨機類別和執行緒安全性」。For the need of a lock, see "The System.Random class and thread safety" in the Random class topic.

備註

呼叫 StartNew 在功能上相當於使用其中一個函式來建立 Task,然後呼叫 @no__t 2 方法來排程執行。Calling StartNew is functionally equivalent to creating a Task using one of its constructors and then calling the Start method to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱使用 .NET 進行平行程式設計中的 <執行 Vs system.threading.tasks.taskfactory.startnew 。For more information and code examples, see Task.Run vs Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<TResult>, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Func<'Result> * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'Result>

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

cancellationToken
CancellationToken

要指派給新工作的 CancellationTokenThe CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制已建立之 Task<TResult> 的行為。A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

scheduler
TaskScheduler

TaskScheduler,用來排程已建立的 Task<TResult>The TaskScheduler that is used to schedule the created Task<TResult>.

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

functionnullfunction is null.

-或--or- schedulernullscheduler is null.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<TResult>)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function);
member this.StartNew : Func<'Result> -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of TResult)) As Task(Of TResult)

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

function 引數為 nullThe function argument is null.

範例

下列範例是簡單的加法應用程式,它會產生兩個亂數字,並提示使用者輸入其總和。The following example is a simple addition app that generates two random numbers and prompts the user to enter their sum. 然後,它會指出答案是否正確,或者,如果使用者的回應不是有效的數位,則會提示使用者重新輸入有效的數位。It then indicates whether the answer is correct or, if the user's response is not a valid number, prompts the user to re-enter a valid number. @No__t-0 是用來建立傳回要加入之亂數字的 Task<TResult> 物件。The StartNew is used to create the Task<TResult> objects that return the random numbers to add.

using System;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      Random rnd = new Random();
      Task<int>[] tasks = new Task<int>[2];
      Object obj = new Object();
      
      while (true) {
         for (int ctr = 0; ctr <= 1; ctr++)
            tasks[ctr] = Task.Factory.StartNew(() => { int i = 0;
                                                       lock(obj) {
                                                          i = rnd.Next(101);
                                                       }
                                                       return i; });

         Task.WaitAll(tasks);
         int n1 = tasks[0].Result;
         int n2 = tasks[1].Result;
         int result = n1 + n2;
         bool validInput = false;
         while (! validInput) {
            ShowMessage(n1, n2);
            string userInput = Console.ReadLine();
            // Process user input.
            if (userInput.Trim().ToUpper() == "X") return;
            int answer;
            validInput = Int32.TryParse(userInput, out answer);
            if (! validInput)
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ");
            else if (answer == result)
               Console.WriteLine("Correct!");
            else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result);
         }
      }
   }

   private static void ShowMessage(int n1, int n2)
   {
      Console.WriteLine("\nEnter 'x' to exit...");
      Console.Write("{0} + {1} = ", n1, n2);
   }
}
// The example displays the following output:
//       Enter 'x' to exit...
//       15 + 11 = 26
//       Correct!
//
//       Enter 'x' to exit...
//       75 + 33 = adc
//       Invalid input. Try again, but enter only numbers.
//
//       Enter 'x' to exit...
//       75 + 33 = 108
//       Correct!
//
//       Enter 'x' to exit...
//       67 + 55 = 133
//       Incorrect. The correct answer is 122.
//
//       Enter 'x' to exit...
//       92 + 51 = 133
//       Incorrect. The correct answer is 143.
//
//       Enter 'x' to exit...
//       81 + 65 = x
   
Imports System.Threading.Tasks

Module AdditionTester
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks(1) As Task(Of Integer)
      Dim obj As New Object()
      
      Do While True
         For ctr As Integer = 0 To 1
            tasks(ctr) = Task.Factory.StartNew(Function()
                                                  Dim i As Integer
                                                  SyncLock(obj)
                                                     i = rnd.Next(101)
                                                  End SyncLock
                                                  Return i
                                               End Function)
         Next
         Task.WaitAll(tasks)
         Dim n1 As Integer = tasks(0).Result
         Dim n2 As Integer = tasks(1).Result
         Dim result As Integer = n1 + n2
         Dim validInput As Boolean = False
         Do While Not validInput
            ShowMessage(n1, n2)
            Dim userInput As String = Console.ReadLine()
            ' Process user input.
            If userInput.Trim().ToUpper = "X" Then Exit Sub
            Dim answer As Integer
            validInput = Int32.TryParse(userInput, answer)
            If Not validInput Then
               Console.WriteLine("Invalid input. Try again, but enter only numbers. ")
            Else If answer = result Then
               Console.WriteLine("Correct!")
            Else
               Console.WriteLine("Incorrect. The correct answer is {0}.", result)
            End If
         Loop
      Loop
   End Sub
   
   Private Sub ShowMessage(n1 As Integer, n2 As Integer)
      Console.WriteLine()
      Console.WriteLine("Enter 'x' to exit...")
      Console.Write("{0} + {1} = ", n1, n2)
   End Sub
End Module
' The example displays output like the following:
'       Enter 'x' to exit...
'       15 + 11 = 26
'       Correct!
'
'       Enter 'x' to exit...
'       75 + 33 = adc
'       Invalid input. Try again, but enter only numbers.
'
'       Enter 'x' to exit...
'       75 + 33 = 108
'       Correct!
'
'       Enter 'x' to exit...
'       67 + 55 = 133
'       Incorrect. The correct answer is 122.
'
'       Enter 'x' to exit...
'       92 + 51 = 133
'       Incorrect. The correct answer is 143.
'
'       Enter 'x' to exit...
'       81 + 65 = x

備註

呼叫 StartNew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以呼叫 Task.Run<TResult>(Func<TResult>) 方法來快速呼叫 StartNew 與預設參數。Starting with the .NET Framework 4.5.NET Framework 4.5, you can call the Task.Run<TResult>(Func<TResult>) method as a quick way to call StartNew with default parameters. 不過,請注意,與 @no__t 有關的兩個方法之間的行為差異,預設不允許以 TaskCreationOptions.AttachedToParent 選項啟動的子工作附加至目前的 Task<TResult> 實例,而 StartNew<TResult>(Func<TResult>) 則會執行此作業。Note, however, that there is a difference in behavior between the two methods regarding : Task.Run<TResult>(Func<TResult>) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>) does. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<Object,TResult>, Object)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state);
member this.StartNew : Func<obj, 'Result> * obj -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of Object, TResult), state As Object) As Task(Of TResult)

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<Object,TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

state
Object

物件,包含 function 委派要使用的資料。An object containing data to be used by the function delegate.

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

functionnullfunction is null.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<TResult>, CancellationToken)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

cancellationToken
CancellationToken

CancellationToken,將指派給新的 TaskThe CancellationToken that will be assigned to the new Task

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

functionnullfunction is null.

範例

下列範例會使用兩個工作來計算以 F100 = F100-1 + F100-2 結尾的數列序列,其種子值為 F1 = 1,F2 = 1,F1 = 0,F2 = 1。The following example uses two tasks to compute the Fibonacci sequence ending in F100 = F100-1 + F100-2 with seed values F1= 1, F2 = 1 and F1 = 0, F2= 1. 大約一半的時間,解除標記會在作業執行時設定。Approximately half of the time, a cancellation token is set as the operations execute. 此範例的輸出會顯示兩個工作順利完成時的結果,以及是否解除標記。The output from the example shows the result if the two tasks complete successfully and if the token is cancelled.

using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      var rnd = new Random();
      var tasks = new List<Task<BigInteger[]>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      for (int ctr = 0; ctr <= 1; ctr++) {
         int start = ctr;
         tasks.Add(Task.Run( () => { BigInteger[] sequence = new BigInteger[100];
                                     sequence[0] = start;
                                     sequence[1] = 1;
                                     for (int index = 2; index <= sequence.GetUpperBound(0); index++) {
                                        token.ThrowIfCancellationRequested();
                                        sequence[index] = sequence[index - 1] + sequence[index - 2];
                                     }
                                     return sequence;
                                   }, token));
      }
      if (rnd.Next(0, 2) == 1)
         source.Cancel();
      try {
         Task.WaitAll(tasks.ToArray());
         foreach (var t in tasks)
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result[0], t.Result[1],
                              t.Result[99]);
      }
      catch (AggregateException e) {
         foreach (var ex in e.InnerExceptions)
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message);
      }
   }
}
// The example displays either the following output:
//    0, 1...218,922,995,834,555,169,026
//    1, 1...354,224,848,179,261,915,075
// or the following output:
//    TaskCanceledException: A task was canceled.
//    TaskCanceledException: A task was canceled.
Imports System.Collections.Generic
Imports System.Numerics
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim rnd As New Random()
      Dim tasks As New List(Of Task(Of BigInteger()))
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      For ctr As Integer = 0 To 1
         Dim start As Integer = ctr
         tasks.Add(Task.Run(Function()
                               Dim sequence(99) As BigInteger
                               sequence(0) = start
                               sequence(1) = 1
                               For index As Integer = 2 To sequence.GetUpperBound(0)
                                  token.ThrowIfCancellationRequested()
                                  sequence(index) = sequence(index - 1) + sequence(index - 2)
                               Next
                               Return sequence
                            End Function, token))
      Next
      If rnd.Next(0, 2) = 1 Then source.Cancel
      Try
         Task.WaitAll(tasks.ToArray())
         For Each t In tasks
            Console.WriteLine("{0}, {1}...{2:N0}", t.Result(0), t.Result(1),
                              t.Result(99))
         Next
      Catch e As AggregateException
         For Each ex In e.InnerExceptions
            Console.WriteLine("{0}: {1}", ex.GetType().Name, ex.Message)
         Next
      End Try
   End Sub
End Module
' The example displays either the following output:
'    0, 1...218,922,995,834,555,169,026
'    1, 1...354,224,848,179,261,915,075
' or the following output:
'    TaskCanceledException: A task was canceled.
'    TaskCanceledException: A task was canceled.

備註

呼叫 StartNew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以使用 Task.Run<TResult>(Func<TResult>, CancellationToken) 方法來快速地呼叫 StartNew<TResult>(Func<TResult>, CancellationToken) 與預設參數。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Task.Run<TResult>(Func<TResult>, CancellationToken) method as a quick way to call StartNew<TResult>(Func<TResult>, CancellationToken) with default parameters. 不過,請注意,與 @no__t 有關的兩個方法之間的行為差異,預設不允許以 TaskCreationOptions.AttachedToParent 選項啟動的子工作附加至目前的 Task<TResult> 實例,而 StartNew<TResult>(Func<TResult>, CancellationToken) 則會執行此作業。Note, however, that there is a difference in behavior between the two methods regarding : Task.Run<TResult>(Func<TResult>, CancellationToken) by default does not allow child tasks started with the TaskCreationOptions.AttachedToParent option to attach to the current Task<TResult> instance, whereas StartNew<TResult>(Func<TResult>, CancellationToken) does. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<TResult>, TaskCreationOptions)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<TResult> ^ function, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<TResult> function, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Func<'Result> * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of TResult), creationOptions As TaskCreationOptions) As Task(Of TResult)

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制已建立之 Task<TResult> 的行為。A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

functionnullfunction is null.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken);
member this.StartNew : Func<obj, 'Result> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<Object,TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

state
Object

物件,包含 function 委派要使用的資料。An object containing data to be used by the function delegate.

cancellationToken
CancellationToken

CancellationToken,將指派給新的 TaskThe CancellationToken that will be assigned to the new Task

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

functionnullfunction is null.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<Object,TResult>, Object, TaskCreationOptions)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
member this.StartNew : Func<obj, 'Result> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task<'Result>
Public Function StartNew(Of TResult) (function As Func(Of Object, TResult), state As Object, creationOptions As TaskCreationOptions) As Task(Of TResult)

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<Object,TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

state
Object

物件,包含 function 委派要使用的資料。An object containing data to be used by the function delegate.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制已建立之 Task<TResult> 的行為。A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

functionnullfunction is null.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

StartNew<TResult>(Func<Object,TResult>, Object, CancellationToken, TaskCreationOptions, TaskScheduler)

建立並啟動 Task<TResult>Creates and starts a Task<TResult>.

public:
generic <typename TResult>
 System::Threading::Tasks::Task<TResult> ^ StartNew(Func<System::Object ^, TResult> ^ function, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions, System::Threading::Tasks::TaskScheduler ^ scheduler);
public System.Threading.Tasks.Task<TResult> StartNew<TResult> (Func<object,TResult> function, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions, System.Threading.Tasks.TaskScheduler scheduler);
member this.StartNew : Func<obj, 'Result> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions * System.Threading.Tasks.TaskScheduler -> System.Threading.Tasks.Task<'Result>

類型參數

TResult

透過 Task<TResult> 取得的結果類型。The type of the result available through the Task<TResult>.

參數

function
Func<Object,TResult>

函式委派,會傳回將可透過 Task<TResult> 使用的未來結果。A function delegate that returns the future result to be available through the Task<TResult>.

state
Object

物件,包含 function 委派要使用的資料。An object containing data to be used by the function delegate.

cancellationToken
CancellationToken

要指派給新工作的 CancellationTokenThe CancellationToken that will be assigned to the new task.

creationOptions
TaskCreationOptions

TaskCreationOptions 值,可控制已建立之 Task<TResult> 的行為。A TaskCreationOptions value that controls the behavior of the created Task<TResult>.

scheduler
TaskScheduler

TaskScheduler,用來排程已建立的 Task<TResult>The TaskScheduler that is used to schedule the created Task<TResult>.

傳回

啟動的 Task<TResult>The started Task<TResult>.

例外狀況

提供的 CancellationToken 已經過處置。The provided CancellationToken has already been disposed.

functionnullfunction is null.

-或--or- schedulernullscheduler is null.

備註

呼叫 System.threading.tasks.taskfactory.startnew 在功能上相當於使用其中一個函式來建立 Task<TResult>,然後呼叫 Start 來排程執行。Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.

.NET Framework 4.5.NET Framework 4.5 開始,您可以搭配使用 Run 方法與 @no__t 2 物件,做為使用預設參數來呼叫 StartNew 的快速方式。Starting with the .NET Framework 4.5.NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters. 如需詳細資訊和程式碼範例,請參閱專案 [Task 與System.threading.tasks.taskfactory.startnew @ no__t-0 在平行程式設計中使用 .NET blog。For more information and code examples, see the entry Task.Run vs. Task.Factory.StartNew in the Parallel Programming with .NET blog.

另請參閱

適用於