共用方式為


Task.Run 方法

定義

將指定的工作排入佇列,以在 ThreadPool 上執行,並傳回該工作的工作或 Task<TResult> 句柄。

多載

Run(Func<Task>, CancellationToken)

將指定的工作排入佇列,以在線程集區上執行,並針對 function所傳回的工作傳回 Proxy。 取消令牌可讓工作在尚未啟動時取消。

Run(Action, CancellationToken)

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task 物件。 取消令牌可讓工作在尚未啟動時取消。

Run(Func<Task>)

將指定的工作排入佇列,以在線程集區上執行,並針對 function所傳回的工作傳回 Proxy。

Run(Action)

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task 物件。

Run<TResult>(Func<Task<TResult>>)

將指定的工作排入佇列,以在線程集區上執行,並傳回 function所傳回之 Task(TResult) 的 Proxy。 取消令牌可讓工作在尚未啟動時取消。

Run<TResult>(Func<TResult>)

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task<TResult> 物件。 取消令牌可讓工作在尚未啟動時取消。

Run<TResult>(Func<Task<TResult>>, CancellationToken)

將指定的工作排入佇列,以在線程集區上執行,並傳回 function所傳回之 Task(TResult) 的 Proxy。

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

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task(TResult) 物件。

備註

Run 方法提供一組多載,可讓您輕鬆地使用預設值啟動工作。 這是 StartNew 多載的輕量型替代方案。

Run(Func<Task>, CancellationToken)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並針對 function所傳回的工作傳回 Proxy。 取消令牌可讓工作在尚未啟動時取消。

public:
 static System::Threading::Tasks::Task ^ Run(Func<System::Threading::Tasks::Task ^> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task> function, System.Threading.CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task?> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<System.Threading.Tasks.Task> * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Shared Function Run (function As Func(Of Task), cancellationToken As CancellationToken) As Task

參數

function
Func<Task>

異步執行的工作。

cancellationToken
CancellationToken

取消標記,如果尚未啟動,可用來取消工作。 Run(Func<Task>, CancellationToken) 不會將 cancellationToken 傳遞至 action

傳回

工作,表示由 function所傳回之工作的 Proxy。

例外狀況

function 參數 null

工作已取消。 此例外狀況會儲存在傳回的工作中。

已處置與 cancellationToken 相關聯的 CancellationTokenSource

工作已取消。

備註

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

Run(Action, CancellationToken)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task 物件。 取消令牌可讓工作在尚未啟動時取消。

public:
 static System::Threading::Tasks::Task ^ Run(Action ^ action, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task Run (Action action, System.Threading.CancellationToken cancellationToken);
static member Run : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Shared Function Run (action As Action, cancellationToken As CancellationToken) As Task

參數

action
Action

異步執行的工作。

cancellationToken
CancellationToken

取消標記,如果尚未啟動,可用來取消工作。 Run(Action, CancellationToken) 不會將 cancellationToken 傳遞至 action

傳回

工作,表示在線程集區中執行的工作佇列。

例外狀況

action 參數 null

工作已取消。 此例外狀況會儲存在傳回的工作中。

已處置與 cancellationToken 相關聯的 CancellationTokenSource

工作已取消。

範例

下列範例會呼叫 Run(Action, CancellationToken) 方法來建立工作,以反覆運算 C:\Windows\System32 目錄中的檔案。 Lambda 表達式會呼叫 Parallel.ForEach 方法,將每個檔案的相關信息新增至 List<T> 物件。 Parallel.ForEach 迴圈叫用的每個中斷連結巢狀工作都會檢查取消令牌的狀態,如果要求取消,則會呼叫 CancellationToken.ThrowIfCancellationRequested 方法。 當呼叫線程呼叫 Task.Wait 方法時,CancellationToken.ThrowIfCancellationRequested 方法會擲回在 catch 區塊中處理的 OperationCanceledException 例外狀況。

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

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

      var t = Task.Run( () => { 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);
      await Task.Yield();
      tokenSource.Cancel();
      try {
         await t;
         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.
//          TaskCanceledException: A task was canceled.
//          ...
//       
//       Task status: Canceled
open System
open System.IO
open System.Threading
open System.Threading.Tasks

let main =
    task {
        use tokenSource = new CancellationTokenSource()
        let token = tokenSource.Token
        let files = ResizeArray()

        let t =
            Task.Run(
                (fun () ->
                    let dir = "C:\\Windows\\System32\\"
                    let obj = obj ()

                    if Directory.Exists dir then
                        Parallel.ForEach(
                            Directory.GetFiles dir,
                            (fun f ->
                                if token.IsCancellationRequested then
                                    token.ThrowIfCancellationRequested()

                                let fi = FileInfo f
                                lock obj (fun () -> files.Add(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc)))
                        )
                        |> ignore),
                token
            )

        do! Task.Yield()
        tokenSource.Cancel()

        try
            do! t
            printfn $"Retrieved information for {files.Count} files."

        with :? AggregateException as e ->
            printfn "Exception messages:"

            for ie in e.InnerExceptions do
                printfn $"   {ie.GetType().Name}: {ie.Message}"

            printfn $"Task status: {t.Status}"
    }

main.Wait()


// The example displays the following output:
//       Exception messages:
//          TaskCanceledException: A task was canceled.
//          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.Run( 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

備註

如果在工作開始執行之前要求取消,工作就不會執行。 相反地,它會設定為 Canceled 狀態,並擲回 TaskCanceledException 例外狀況。

Run(Action, CancellationToken) 方法是較簡單的 TaskFactory.StartNew(Action, CancellationToken) 方法替代方案。 它會建立具有下列預設值的工作:

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

Run(Func<Task>)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並針對 function所傳回的工作傳回 Proxy。

public:
 static System::Threading::Tasks::Task ^ Run(Func<System::Threading::Tasks::Task ^> ^ function);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task> function);
public static System.Threading.Tasks.Task Run (Func<System.Threading.Tasks.Task?> function);
static member Run : Func<System.Threading.Tasks.Task> -> System.Threading.Tasks.Task
Public Shared Function Run (function As Func(Of Task)) As Task

參數

function
Func<Task>

異步執行的工作。

傳回

工作,表示由 function所傳回之工作的 Proxy。

例外狀況

function 參數 null

備註

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

Run(Action)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task 物件。

public:
 static System::Threading::Tasks::Task ^ Run(Action ^ action);
public static System.Threading.Tasks.Task Run (Action action);
static member Run : Action -> System.Threading.Tasks.Task
Public Shared Function Run (action As Action) As Task

參數

action
Action

異步執行的工作。

傳回

工作,表示排入佇列以在 ThreadPool 中執行的工作。

例外狀況

action 參數 null

範例

下列範例會定義 ShowThreadInfo 方法,以顯示目前線程的 Thread.ManagedThreadId。 它會直接從應用程式線程呼叫,並從傳遞至 Run(Action) 方法的 Action 委派呼叫。

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

public class Example
{
   public static void Main()
   {
      ShowThreadInfo("Application");

      var t = Task.Run(() => ShowThreadInfo("Task") );
      t.Wait();
   }

   static void ShowThreadInfo(String s)
   {
      Console.WriteLine("{0} thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId);
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3
open System.Threading
open System.Threading.Tasks

let showThreadInfo s =
    printfn $"%s{s} thread ID: {Thread.CurrentThread.ManagedThreadId}"

showThreadInfo "Application"

let t = Task.Run(fun () -> showThreadInfo "Task")
t.Wait()

// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      ShowThreadInfo("Application")

      Dim t As Task = Task.Run(Sub() ShowThreadInfo("Task") )
      t.Wait()
   End Sub
   
   Private Sub ShowThreadInfo(s As String)
      Console.WriteLine("{0} Thread ID: {1}",
                        s, Thread.CurrentThread.ManagedThreadId)
   End Sub
End Module
' The example displays output like the following:
'    Application thread ID: 1
'    Task thread ID: 3

下列範例與上一個範例類似,不同之處在於它會使用 Lambda 表達式來定義工作要執行的程式代碼。

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

public class Example
{
   public static void Main()
   {
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId);
      var t = Task.Run(() => {  Console.WriteLine("Task thread ID: {0}",
                                   Thread.CurrentThread.ManagedThreadId);
                             } );
      t.Wait();
   }
}
// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3
open System.Threading
open System.Threading.Tasks

printfn $"Application thread ID: {Thread.CurrentThread.ManagedThreadId}"
let t = Task.Run(fun () -> printfn $"Task thread ID: {Thread.CurrentThread.ManagedThreadId}")
t.Wait()

// The example displays the following output:
//       Application thread ID: 1
//       Task thread ID: 3
Imports System.Threading
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Console.WriteLine("Application thread ID: {0}",
                        Thread.CurrentThread.ManagedThreadId)
      Dim t As Task = Task.Run(Sub()
                                  Console.WriteLine("Task thread ID: {0}",
                                                    Thread.CurrentThread.ManagedThreadId)
                               End Sub)
      t.Wait()
   End Sub
End Module
' The example displays output like the following:
'    Application thread ID: 1
'    Task thread ID: 3

這些範例顯示異步工作在與主要應用程式線程不同的線程上執行。

呼叫 Wait 方法可確保工作在應用程式結束之前完成並顯示其輸出。 否則,Main 方法有可能在工作完成之前完成。

下列範例說明 Run(Action) 方法。 它會定義目錄名稱的陣列,並啟動個別的工作來擷取每個目錄中的檔名。 所有工作都會將檔名寫入單一 ConcurrentBag<T> 物件。 然後,此範例會呼叫 WaitAll(Task[]) 方法,以確保所有工作都已完成,然後顯示寫入至 ConcurrentBag<T> 對象的檔名總數。

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

public class Example
{
   public static void Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = Task.Run( () => { foreach(var path in Directory.GetFiles(dirName)) 
                                       list.Add(path); }  );
         tasks.Add(t);
      }
      Task.WaitAll(tasks.ToArray());
      foreach (Task t in tasks)
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status);
         
      Console.WriteLine("Number of files read: {0}", list.Count);
   }
}
// The example displays output like the following:
//       Task 1 Status: RanToCompletion
//       Task 2 Status: RanToCompletion
//       Number of files read: 23
open System.Collections.Concurrent
open System.IO
open System.Threading.Tasks

let list = ConcurrentBag<string>()
let dirNames = [ "."; ".." ]
let tasks = ResizeArray()

for dirName in dirNames do
    let t =
        Task.Run(fun () ->
            for path in Directory.GetFiles dirName do
                list.Add path)

    tasks.Add t

tasks.ToArray() |> Task.WaitAll

for t in tasks do
    printfn $"Task {t.Id} Status: {t.Status}"

printfn $"Number of files read: {list.Count}"

// The example displays output like the following:
//       Task 1 Status: RanToCompletion
//       Task 2 Status: RanToCompletion
//       Number of files read: 23
Imports System.Collections.Concurrent
Imports System.Collections.Generic
Imports System.IO
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim list As New ConcurrentBag(Of String)()
      Dim dirNames() As String = { ".", ".." }
      Dim tasks As New List(Of Task)()
      For Each dirName In dirNames 
         Dim t As Task = Task.Run( Sub()
                                      For Each path In Directory.GetFiles(dirName) 
                                         list.Add(path)
                                      Next
                                   End Sub  )
         tasks.Add(t)
      Next
      Task.WaitAll(tasks.ToArray())
      For Each t In tasks
         Console.WriteLine("Task {0} Status: {1}", t.Id, t.Status)
      Next   
      Console.WriteLine("Number of files read: {0}", list.Count)
   End Sub
End Module
' The example displays output like the following:
'       Task 1 Status: RanToCompletion
'       Task 2 Status: RanToCompletion
'       Number of files read: 23

備註

Run 方法可讓您在單一方法呼叫中建立和執行工作,而且是 StartNew 方法更簡單的替代方案。 它會建立具有下列預設值的工作:

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

Run<TResult>(Func<Task<TResult>>)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並傳回 function所傳回之 Task(TResult) 的 Proxy。 取消令牌可讓工作在尚未啟動時取消。

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

類型參數

TResult

Proxy 工作所傳回之結果的類型。

參數

function
Func<Task<TResult>>

異步執行的工作。

傳回

Task(TResult),表示 function所傳回之 Task(TResult) 的 Proxy。

例外狀況

function 參數 null

備註

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

Run<TResult>(Func<TResult>)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task<TResult> 物件。 取消令牌可讓工作在尚未啟動時取消。

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

類型參數

TResult

工作的傳回型別。

參數

function
Func<TResult>

異步執行的工作。

傳回

工作物件,表示佇列在線程集區中執行的工作。

例外狀況

function 參數是 null

範例

下列範例會計算代表已發行書籍之文本檔中大約字數。 每項工作都會負責開啟檔案、以異步方式讀取其整個內容,以及使用正則表達式計算字數。 系統會呼叫 WaitAll(Task[]) 方法,以確保所有工作都已完成,再將每本書的字數計數顯示到控制台。

using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

public class Example
{
   public static void Main()
   {
      string pattern = @"\p{P}*\s+";
      string[] titles = { "Sister Carrie", "The Financier" };
      Task<int>[] tasks = new Task<int>[titles.Length];

      for (int ctr = 0; ctr < titles.Length; ctr++) {
         string s = titles[ctr];
         tasks[ctr] = Task.Run( () => {
                                   // Number of words.
                                   int nWords = 0;
                                   // Create filename from title.
                                   string fn = s + ".txt";
                                   if (File.Exists(fn)) {
                                      StreamReader sr = new StreamReader(fn);
                                      string input = sr.ReadToEndAsync().Result;
                                      nWords = Regex.Matches(input, pattern).Count;
                                   }
                                   return nWords;
                                } );
      }
      Task.WaitAll(tasks);

      Console.WriteLine("Word Counts:\n");
      for (int ctr = 0; ctr < titles.Length; ctr++)
         Console.WriteLine("{0}: {1,10:N0} words", titles[ctr], tasks[ctr].Result);
   }
}
// The example displays the following output:
//       Sister Carrie:    159,374 words
//       The Financier:    196,362 words
open System
open System.IO
open System.Text.RegularExpressions
open System.Threading.Tasks

let pattern = @"\p{P}*\s+"
let titles = [| "Sister Carrie"; "The Financier" |]

let tasks =
    Array.map (fun title ->
        Task.Run(fun () ->
            // Create filename from title.
            let fn = title + ".txt"

            if File.Exists fn then
                use sr = new StreamReader(fn)
                let input = sr.ReadToEndAsync().Result
                Regex.Matches(input, pattern).Count
            else
                0)) titles

tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll

printfn "Word Counts:\n"

for i = 0 to tasks.Length - 1 do
    printfn $"%s{titles.[i]}: %10d{tasks.[i].Result} words"

// The example displays the following output:
//       Sister Carrie:    159,374 words
//       The Financier:    196,362 words
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim pattern As String = "\p{P}*\s+"
      Dim titles() As String = { "Sister Carrie",
                                 "The Financier" }
      Dim tasks(titles.Length - 1) As Task(Of Integer)

      For ctr As Integer = 0 To titles.Length - 1
         Dim s As String = titles(ctr)
         tasks(ctr) = Task.Run( Function()
                                   ' Number of words.
                                   Dim nWords As Integer = 0
                                   ' Create filename from title.
                                   Dim fn As String = s + ".txt"
                                   If File.Exists(fn) Then
                                      Dim sr As New StreamReader(fn)
                                      Dim input As String = sr.ReadToEndAsync().Result
                                      nWords = Regex.Matches(input, pattern).Count
                                   End If
                                   Return nWords
                                End Function)
      Next
      Task.WaitAll(tasks)

      Console.WriteLine("Word Counts:")
      Console.WriteLine()
      For ctr As Integer = 0 To titles.Length - 1
         Console.WriteLine("{0}: {1,10:N0} words", titles(ctr), tasks(ctr).Result)
      Next
   End Sub
End Module
' The example displays the following output:
'       Sister Carrie:    159,374 words
'       The Financier:    196,362 words

正則表達式 \p{P}*\s+ 符合零、一或多個標點符號字元,後面接著一或多個空格符。 它假設相符項目的總數等於近似字數。

備註

Run 方法是較簡單的 TaskFactory.StartNew(Action) 方法替代方案。 它會建立具有下列預設值的工作:

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

Run<TResult>(Func<Task<TResult>>, CancellationToken)

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並傳回 function所傳回之 Task(TResult) 的 Proxy。

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ Run(Func<System::Threading::Tasks::Task<TResult> ^> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>> function, System.Threading.CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<System.Threading.Tasks.Task<TResult>?> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<System.Threading.Tasks.Task<'Result>> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of Task(Of TResult)), cancellationToken As CancellationToken) As Task(Of TResult)

類型參數

TResult

Proxy 工作所傳回之結果的類型。

參數

function
Func<Task<TResult>>

異步執行的工作。

cancellationToken
CancellationToken

取消標記,如果尚未啟動,可用來取消工作。 Run<TResult>(Func<Task<TResult>>, CancellationToken) 不會將 cancellationToken 傳遞至 action

傳回

Task(TResult),表示 function所傳回之 Task(TResult) 的 Proxy。

例外狀況

function 參數 null

工作已取消。 此例外狀況會儲存在傳回的工作中。

已處置與 cancellationToken 相關聯的 CancellationTokenSource

工作已取消。

備註

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於

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

來源:
Task.cs
來源:
Task.cs
來源:
Task.cs

將指定的工作排入佇列,以在線程集區上執行,並傳回代表該工作的 Task(TResult) 物件。

public:
generic <typename TResult>
 static System::Threading::Tasks::Task<TResult> ^ Run(Func<TResult> ^ function, System::Threading::CancellationToken cancellationToken);
public static System.Threading.Tasks.Task<TResult> Run<TResult> (Func<TResult> function, System.Threading.CancellationToken cancellationToken);
static member Run : Func<'Result> * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Result>
Public Shared Function Run(Of TResult) (function As Func(Of TResult), cancellationToken As CancellationToken) As Task(Of TResult)

類型參數

TResult

工作的結果類型。

參數

function
Func<TResult>

異步執行的工作。

cancellationToken
CancellationToken

取消標記,如果尚未啟動,可用來取消工作。 Run<TResult>(Func<TResult>, CancellationToken) 不會將 cancellationToken 傳遞至 action

傳回

Task(TResult),表示佇列在線程集區中執行的工作。

例外狀況

function 參數是 null

工作已取消。 此例外狀況會儲存在傳回的工作中。

已處置與 cancellationToken 相關聯的 CancellationTokenSource

工作已取消。

範例

下列範例會建立 20 個工作,將循環執行,直到計數器遞增為 2 百萬個值為止。 當前 10 個工作達到 200 萬個時,取消令牌就會取消,而且任何計數器尚未達到 200 萬的工作會取消。 此範例會顯示可能的輸出。

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

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                         token.ThrowIfCancellationRequested();
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
      }
   }
}
// The example displays output like the following:
//    Waiting for the first 10 tasks to complete...
//    Status of tasks:
//
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10             Canceled            n/a
//            11             Canceled            n/a
//            12             Canceled            n/a
//            13             Canceled            n/a
//            14             Canceled            n/a
//            15             Canceled            n/a
//            16      RanToCompletion      2,000,000
//            17             Canceled            n/a
//            18             Canceled            n/a
//            19             Canceled            n/a
//            20             Canceled            n/a
open System
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks

let source = new CancellationTokenSource()
let token = source.Token
let mutable completedIterations = 0

let tasks =
    [| for _ = 0 to 19 do
           Task.Run(
               (fun () ->
                   let mutable iterations = 0

                   for _ = 1 to 2000000 do
                       token.ThrowIfCancellationRequested()
                       iterations <- iterations + 1

                   Interlocked.Increment &completedIterations |> ignore

                   if completedIterations >= 10 then
                       source.Cancel()

                   iterations),
               token
           )

       |]

printfn "Waiting for the first 10 tasks to complete...\n"

try
    tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll
with :? AggregateException ->
    printfn "Status of tasks:\n"
    printfn "%10s %20s %14s" "Task Id" "Status" "Iterations"

    for t in tasks do
        if t.Status <> TaskStatus.Canceled then
            t.Result.ToString "N0"
        else
            "n/a"
        |> printfn "%10i %20O %14s" t.Id t.Status


// The example displays output like the following:
//    Waiting for the first 10 tasks to complete...
//    Status of tasks:
//
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10             Canceled            n/a
//            11             Canceled            n/a
//            12             Canceled            n/a
//            13             Canceled            n/a
//            14             Canceled            n/a
//            15             Canceled            n/a
//            16      RanToCompletion      2,000,000
//            17             Canceled            n/a
//            18             Canceled            n/a
//            19             Canceled            n/a
//            20             Canceled            n/a
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example

   Public Sub Main()
      Dim tasks As New List(Of Task(Of Integer))()
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      Dim completedIterations As Integer = 0
      
      For n As Integer = 0 To 19
         tasks.Add(Task.Run( Function()
                                Dim iterations As Integer= 0
                                For ctr As Long = 1 To 2000000
                                   token.ThrowIfCancellationRequested()
                                   iterations += 1
                                Next
                                Interlocked.Increment(completedIterations)
                                If completedIterations >= 10 Then source.Cancel()
                                Return iterations
                             End Function, token))
      Next

      Console.WriteLine("Waiting for the first 10 tasks to complete... ")
      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         Console.WriteLine("Status of tasks:")
         Console.WriteLine()
         Console.WriteLine("{0,10} {1,20} {2,14}", "Task Id",
                           "Status", "Iterations")
         For Each t In tasks
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              If(t.Status <> TaskStatus.Canceled,
                                 t.Result.ToString("N0"), "n/a"))
         Next
      End Try
   End Sub
End Module
' The example displays output like the following:
'    Waiting for the first 10 tasks to complete...
'    Status of tasks:
'
'       Task Id               Status     Iterations
'             1      RanToCompletion      2,000,000
'             2      RanToCompletion      2,000,000
'             3      RanToCompletion      2,000,000
'             4      RanToCompletion      2,000,000
'             5      RanToCompletion      2,000,000
'             6      RanToCompletion      2,000,000
'             7      RanToCompletion      2,000,000
'             8      RanToCompletion      2,000,000
'             9      RanToCompletion      2,000,000
'            10             Canceled            n/a
'            11             Canceled            n/a
'            12             Canceled            n/a
'            13             Canceled            n/a
'            14             Canceled            n/a
'            15             Canceled            n/a
'            16      RanToCompletion      2,000,000
'            17             Canceled            n/a
'            18             Canceled            n/a
'            19             Canceled            n/a
'            20             Canceled            n/a

此範例會反覆運算所有工作,以判斷哪些工作已完成且已取消,而不是使用 InnerExceptions 屬性來檢查例外狀況。 針對已完成的專案,它會顯示工作所傳回的值。

由於取消是合作的,因此每個工作都可以決定如何回應取消。 下列範例就像第一個範例,不同之處在於,一旦取消令牌,工作就會傳回他們已完成的反覆項目數目,而不是擲回例外狀況。

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

public class Example
{
   public static void Main()
   {
      var tasks = new List<Task<int>>();
      var source = new CancellationTokenSource();
      var token = source.Token;
      int completedIterations = 0;

      for (int n = 0; n <= 19; n++)
         tasks.Add(Task.Run( () => { int iterations = 0;
                                     for (int ctr = 1; ctr <= 2000000; ctr++) {
                                         if (token.IsCancellationRequested)
                                            return iterations;
                                         iterations++;
                                     }
                                     Interlocked.Increment(ref completedIterations);
                                     if (completedIterations >= 10)
                                        source.Cancel();
                                     return iterations; }, token));

      Console.WriteLine("Waiting for the first 10 tasks to complete...\n");
      try  {
         Task.WaitAll(tasks.ToArray());
      }
      catch (AggregateException) {
         Console.WriteLine("Status of tasks:\n");
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations");
         foreach (var t in tasks)
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              t.Status != TaskStatus.Canceled ? t.Result.ToString("N0") : "n/a");
      }
   }
}
// The example displays output like the following:
//    Status of tasks:
//
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10      RanToCompletion      1,658,326
//            11      RanToCompletion      1,988,506
//            12      RanToCompletion      2,000,000
//            13      RanToCompletion      1,942,246
//            14      RanToCompletion        950,108
//            15      RanToCompletion      1,837,832
//            16      RanToCompletion      1,687,182
//            17      RanToCompletion        194,548
//            18             Canceled    Not Started
//            19             Canceled    Not Started
//            20             Canceled    Not Started
open System
open System.Collections.Generic
open System.Threading
open System.Threading.Tasks

let source = new CancellationTokenSource()
let token = source.Token
let mutable completedIterations = 0

let tasks =
    [| for _ = 0 to 19 do
           Task.Run(
               (fun () ->
                   let mutable iterations = 0

                   for _ = 1 to 2000000 do
                       token.ThrowIfCancellationRequested()
                       iterations <- iterations + 1

                   Interlocked.Increment &completedIterations |> ignore

                   if completedIterations >= 10 then
                       source.Cancel()

                   iterations),
               token
           ) |]

printfn "Waiting for the first 10 tasks to complete...\n"

try
    tasks |> Seq.cast |> Array.ofSeq |> Task.WaitAll

with :? AggregateException ->
    printfn "Status of tasks:\n"
    printfn "%10s %20s %14s" "Task Id" "Status" "Iterations"

    for t in tasks do
        if t.Status <> TaskStatus.Canceled then
            t.Result.ToString "N0"
        else
            "n/a"
        |> printfn "%10i %20O %14s" t.Id t.Status

// The example displays output like the following:
//    Status of tasks:
//
//       Task Id               Status     Iterations
//             1      RanToCompletion      2,000,000
//             2      RanToCompletion      2,000,000
//             3      RanToCompletion      2,000,000
//             4      RanToCompletion      2,000,000
//             5      RanToCompletion      2,000,000
//             6      RanToCompletion      2,000,000
//             7      RanToCompletion      2,000,000
//             8      RanToCompletion      2,000,000
//             9      RanToCompletion      2,000,000
//            10      RanToCompletion      1,658,326
//            11      RanToCompletion      1,988,506
//            12      RanToCompletion      2,000,000
//            13      RanToCompletion      1,942,246
//            14      RanToCompletion        950,108
//            15      RanToCompletion      1,837,832
//            16      RanToCompletion      1,687,182
//            17      RanToCompletion        194,548
//            18             Canceled    Not Started
//            19             Canceled    Not Started
//            20             Canceled    Not Started
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks

Module Example

   Public Sub Main()
      Dim tasks As New List(Of Task(Of Integer))()
      Dim source As New CancellationTokenSource
      Dim token As CancellationToken = source.Token
      Dim completedIterations As Integer = 0
      
      For n As Integer = 0 To 19
         tasks.Add(Task.Run( Function()
                                Dim iterations As Integer= 0
                                For ctr As Long = 1 To 2000000
                                   If token.IsCancellationRequested Then
                                      Return iterations
                                   End If
                                   iterations += 1
                                Next
                                Interlocked.Increment(completedIterations)
                                If completedIterations >= 10 Then source.Cancel()
                                Return iterations
                             End Function, token))
      Next

      Try
         Task.WaitAll(tasks.ToArray())
      Catch e As AggregateException
         Console.WriteLine("Status of tasks:")
         Console.WriteLine()
         Console.WriteLine("{0,10} {1,20} {2,14:N0}", "Task Id",
                           "Status", "Iterations")
         For Each t In tasks
            Console.WriteLine("{0,10} {1,20} {2,14}",
                              t.Id, t.Status,
                              If(t.Status <> TaskStatus.Canceled,
                                 t.Result.ToString("N0"), "Not Started"))
         Next
      End Try
   End Sub
End Module
' The example displays output like the following:
'    Status of tasks:
'
'       Task Id               Status     Iterations
'             1      RanToCompletion      2,000,000
'             2      RanToCompletion      2,000,000
'             3      RanToCompletion      2,000,000
'             4      RanToCompletion      2,000,000
'             5      RanToCompletion      2,000,000
'             6      RanToCompletion      2,000,000
'             7      RanToCompletion      2,000,000
'             8      RanToCompletion      2,000,000
'             9      RanToCompletion      2,000,000
'            10      RanToCompletion      1,658,326
'            11      RanToCompletion      1,988,506
'            12      RanToCompletion      2,000,000
'            13      RanToCompletion      1,942,246
'            14      RanToCompletion        950,108
'            15      RanToCompletion      1,837,832
'            16      RanToCompletion      1,687,182
'            17      RanToCompletion        194,548
'            18             Canceled    Not Started
'            19             Canceled    Not Started
'            20             Canceled    Not Started

此範例仍必須處理 AggregateException 例外狀況,因為要求取消時尚未啟動的任何工作仍會擲回例外狀況。

備註

如果在工作開始執行之前要求取消,工作就不會執行。 相反地,它會設定為 Canceled 狀態,並擲回 TaskCanceledException 例外狀況。

Run 方法是較簡單的 StartNew 方法替代方案。 它會建立具有下列預設值的工作:

如需處理工作作業擲回例外狀況的資訊,請參閱 例外狀況處理

另請參閱

適用於