Task Konstruktory

Definicja

Inicjuje nowy Taskelement .

Przeciążenia

Task(Action)

Inicjuje nową Task akcję przy użyciu określonej akcji.

Task(Action, CancellationToken)

Inicjuje nowy Task element z określoną akcją i CancellationToken.

Task(Action, TaskCreationOptions)

Inicjuje nową Task z określoną akcją i opcjami tworzenia.

Task(Action<Object>, Object)

Inicjuje nową Task z określoną akcją i stanem.

Task(Action, CancellationToken, TaskCreationOptions)

Inicjuje nową Task z określoną akcją i opcjami tworzenia.

Task(Action<Object>, Object, CancellationToken)

Inicjuje nową Task akcję, stan i CancellationToken.

Task(Action<Object>, Object, TaskCreationOptions)

Inicjuje nową Task akcję, stan i opcje.

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

Inicjuje nową Task akcję, stan i opcje.

Task(Action)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task akcję przy użyciu określonej akcji.

public:
 Task(Action ^ action);
public Task (Action action);
new System.Threading.Tasks.Task : Action -> System.Threading.Tasks.Task
Public Sub New (action As Action)

Parametry

action
Action

Delegat reprezentujący kod do wykonania w zadaniu.

Wyjątki

Argumentem action jest null.

Przykłady

W poniższym przykładzie użyto konstruktora Task(Action) do tworzenia zadań, które pobierają nazwy plików w określonych katalogach. Wszystkie zadania zapisują nazwy plików w jednym ConcurrentBag<T> obiekcie. W tym przykładzie wywołamy metodę WaitAll(Task[]) , aby upewnić się, że wszystkie zadania zostały ukończone, a następnie wyświetla liczbę całkowitej liczby nazw plików zapisanych w ConcurrentBag<T> obiekcie.

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

public class Example
{
   public static async Task Main()
   {
      var list = new ConcurrentBag<string>();
      string[] dirNames = { ".", ".." };
      List<Task> tasks = new List<Task>();
      foreach (var dirName in dirNames) {
         Task t = new Task( () => { foreach(var path in Directory.GetFiles(dirName))
                                    list.Add(path); }  );
         tasks.Add(t);
         t.Start();
      }
      await Task.WhenAll(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 main =
    task {
        let list = ConcurrentBag<string>()
        let dirNames = [ "."; ".." ]
        let tasks = ResizeArray()

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

            tasks.Add t
            t.Start()

        do! tasks.ToArray() |> Task.WhenAll

        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 New Task( Sub()
                               For Each path In Directory.GetFiles(dirName)
                                  list.Add(path)
                               Next
                            End Sub  )
         tasks.Add(t)
         t.Start()
      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

Poniższy przykład jest identyczny, z tą różnicą, że użyto Run(Action) metody do utworzenia wystąpienia i uruchomienia zadania w jednej operacji. Metoda zwraca Task obiekt reprezentujący zadanie.

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

Uwagi

Ten konstruktor powinien być używany tylko w zaawansowanych scenariuszach, w których wymagane jest oddzielenie tworzenia i uruchamiania zadania.

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomieniem zadania jest wywołanie metody lub TaskFactory.StartNew(Action) statycznejTask.Run(Action).

Jeśli zadanie bez akcji jest potrzebne tylko dla użytkownika interfejsu API, aby mieć coś do oczekiwania, TaskCompletionSource<TResult> należy użyć polecenia .

Zobacz też

Dotyczy

Task(Action, CancellationToken)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nowy Task element z określoną akcją i CancellationToken.

public:
 Task(Action ^ action, System::Threading::CancellationToken cancellationToken);
public Task (Action action, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task : Action * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Sub New (action As Action, cancellationToken As CancellationToken)

Parametry

action
Action

Delegat reprezentujący kod do wykonania w zadaniu.

cancellationToken
CancellationToken

To CancellationToken , które zostanie zaobserwowane przez nowe zadanie.

Wyjątki

Dostarczone CancellationToken zostało już usunięte.

Argument action ma wartość null.

Przykłady

Poniższy przykład wywołuje konstruktora, Task(Action, CancellationToken) aby utworzyć zadanie, które iteruje pliki w katalogu C:\Windows\System32. Wyrażenie lambda wywołuje metodę Parallel.ForEach , aby dodać informacje o każdym pliku do List<T> obiektu. Każde odłączone zagnieżdżone zadanie wywoływane przez Parallel.ForEach pętlę sprawdza stan tokenu anulowania, a jeśli zażądano anulowania, wywołuje metodę CancellationToken.ThrowIfCancellationRequested . Metoda CancellationToken.ThrowIfCancellationRequested zgłasza OperationCanceledException wyjątek obsługiwany w bloku, catch gdy wątek wywołujący wywołuje metodę Task.Wait . Następnie Start metoda jest wywoływana w celu uruchomienia zadania.

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 = new Task(() => { 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);
      t.Start();
      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.
//       
//       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 =
            new Task(
                (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
            )

        t.Start()
        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.
//
//       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 New Task(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)
      t.Start()
      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

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie statycznych Task.Run(Action, CancellationToken) metod i TaskFactory.StartNew(Action, CancellationToken) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Aby uzyskać więcej informacji, zobacz Równoległość zadań (biblioteka równoległa zadań) i Anulowanie w wątkach zarządzanych.

Dotyczy

Task(Action, TaskCreationOptions)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task z określoną akcją i opcjami tworzenia.

public:
 Task(Action ^ action, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action action, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action, creationOptions As TaskCreationOptions)

Parametry

action
Action

Delegat reprezentujący kod do wykonania w zadaniu.

creationOptions
TaskCreationOptions

Służy TaskCreationOptions do dostosowywania zachowania zadania.

Wyjątki

Argument action ma wartość null.

Argument creationOptions określa nieprawidłową wartość dla TaskCreationOptionselementu .

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie metody statycznej TaskFactory.StartNew(Action, TaskCreationOptions) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Dotyczy

Task(Action<Object>, Object)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task z określoną akcją i stanem.

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state);
public Task (Action<object> action, object state);
public Task (Action<object?> action, object? state);
new System.Threading.Tasks.Task : Action<obj> * obj -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object)

Parametry

action
Action<Object>

Delegat reprezentujący kod do wykonania w zadaniu.

state
Object

Obiekt reprezentujący dane, które mają być używane przez akcję.

Wyjątki

Argument action ma wartość null.

Przykłady

W poniższym przykładzie zdefiniowano tablicę 6-literowych wyrazów. Każde słowo jest następnie przekazywane jako argument do Task(Action<Object>, Object) konstruktora, którego Action<T> delegat scramble znaki w słowie, a następnie wyświetla oryginalne słowo i jego wersję scrambled.

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

public class Example
{
   public static async Task 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) {
         Task t = new Task( (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);
         t.Start();
         tasks.Add(t);
      }
      await Task.WhenAll(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
open System
open System.Threading.Tasks

let main =
    task {
        let tasks = ResizeArray()
        let rnd = Random()
        let lockObj = obj ()

        let words6 =
            [ "reason"
              "editor"
              "rioter"
              "rental"
              "senior"
              "regain"
              "ordain"
              "rained" ]

        for word6 in words6 do
            let t =
                new Task(
                    (fun word ->
                        let chars = (string word).ToCharArray()
                        let order = Array.zeroCreate<double> chars.Length

                        lock lockObj (fun () ->
                            for i = 0 to order.Length - 1 do
                                order[i] <- rnd.NextDouble())

                        Array.Sort(order, chars)
                        printfn $"{word} --> {new String(chars)}"),
                    word6
                )

            t.Start()
            tasks.Add t

        do! tasks.ToArray() |> Task.WhenAll
    }

main.Wait()

// 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
         Dim t As New Task( 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)
         t.Start()
         tasks.Add(t)
      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

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie metody statycznej TaskFactory.StartNew(Action<Object>, Object) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Zobacz też

Dotyczy

Task(Action, CancellationToken, TaskCreationOptions)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task z określoną akcją i opcjami tworzenia.

public:
 Task(Action ^ action, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action action, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)

Parametry

action
Action

Delegat reprezentujący kod do wykonania w zadaniu.

cancellationToken
CancellationToken

To CancellationToken , które zostanie zaobserwowane przez nowe zadanie.

creationOptions
TaskCreationOptions

Służy TaskCreationOptions do dostosowywania zachowania zadania.

Wyjątki

CancellationTokenSource Utworzony element cancellationToken został już usunięty.

Argument action ma wartość null.

Argument creationOptions określa nieprawidłową wartość dla TaskCreationOptionselementu .

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie metody statycznej TaskFactory.StartNew(Action, CancellationToken, TaskCreationOptions, TaskScheduler) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Aby uzyskać więcej informacji, zobacz Równoległość zadań (biblioteka równoległa zadań) i Anulowanie zadań.

Dotyczy

Task(Action<Object>, Object, CancellationToken)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task akcję, stan i CancellationToken.

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken);
public Task (Action<object> action, object state, System.Threading.CancellationToken cancellationToken);
public Task (Action<object?> action, object? state, System.Threading.CancellationToken cancellationToken);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.CancellationToken -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, cancellationToken As CancellationToken)

Parametry

action
Action<Object>

Delegat reprezentujący kod do wykonania w zadaniu.

state
Object

Obiekt reprezentujący dane, które mają być używane przez akcję.

cancellationToken
CancellationToken

To CancellationToken , które zostanie zaobserwowane przez nowe zadanie.

Wyjątki

CancellationTokenSource Utworzony element cancellationToken został już usunięty.

Argument action ma wartość null.

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie metody statycznej TaskFactory.StartNew(Action<Object>, Object, CancellationToken) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Dotyczy

Task(Action<Object>, Object, TaskCreationOptions)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task akcję, stan i opcje.

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action<object> action, object state, System.Threading.Tasks.TaskCreationOptions creationOptions);
public Task (Action<object?> action, object? state, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, creationOptions As TaskCreationOptions)

Parametry

action
Action<Object>

Delegat reprezentujący kod do wykonania w zadaniu.

state
Object

Obiekt reprezentujący dane, które mają być używane przez akcję.

creationOptions
TaskCreationOptions

Służy TaskCreationOptions do dostosowywania zachowania zadania.

Wyjątki

Argument action ma wartość null.

Argument creationOptions określa nieprawidłową wartość dla TaskCreationOptionselementu .

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie metody statycznej TaskFactory.StartNew(Action<Object>, Object, TaskCreationOptions) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Dotyczy

Task(Action<Object>, Object, CancellationToken, TaskCreationOptions)

Źródło:
Task.cs
Źródło:
Task.cs
Źródło:
Task.cs

Inicjuje nową Task akcję, stan i opcje.

public:
 Task(Action<System::Object ^> ^ action, System::Object ^ state, System::Threading::CancellationToken cancellationToken, System::Threading::Tasks::TaskCreationOptions creationOptions);
public Task (Action<object> action, object state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
public Task (Action<object?> action, object? state, System.Threading.CancellationToken cancellationToken, System.Threading.Tasks.TaskCreationOptions creationOptions);
new System.Threading.Tasks.Task : Action<obj> * obj * System.Threading.CancellationToken * System.Threading.Tasks.TaskCreationOptions -> System.Threading.Tasks.Task
Public Sub New (action As Action(Of Object), state As Object, cancellationToken As CancellationToken, creationOptions As TaskCreationOptions)

Parametry

action
Action<Object>

Delegat reprezentujący kod do wykonania w zadaniu.

state
Object

Obiekt reprezentujący dane, które mają być używane przez akcję.

cancellationToken
CancellationToken

To CancellationToken , które zostanie zaobserwowane przez nowe zadanie.

creationOptions
TaskCreationOptions

Służy TaskCreationOptions do dostosowywania zachowania zadania.

Wyjątki

CancellationTokenSource Utworzony element cancellationToken został już usunięty.

Argument action ma wartość null.

Argument creationOptions określa nieprawidłową wartość dla TaskCreationOptionselementu .

Uwagi

Zamiast wywoływać ten konstruktor, najczęstszym sposobem utworzenia wystąpienia Task obiektu i uruchomienia zadania jest wywołanie metody statycznej TaskFactory.StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) . Jedyną zaletą tego konstruktora jest możliwość oddzielenia wystąpienia obiektu od wywołania zadania.

Dotyczy