Compartir a través de


Task.Run Método

Definición

Pone en cola el trabajo especificado para ejecutarse en ThreadPool y devuelve una tarea o un identificador Task<TResult> para ese trabajo.

Sobrecargas

Run(Func<Task>, CancellationToken)

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para la tarea devuelta por function. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

Run(Action, CancellationToken)

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task que representa ese trabajo. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

Run(Func<Task>)

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para la tarea devuelta por function.

Run(Action)

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task que representa ese trabajo.

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

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para el Task(TResult) devuelto por function. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

Run<TResult>(Func<TResult>)

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task<TResult> que representa ese trabajo. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

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

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para el Task(TResult) devuelto por function.

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

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task(TResult) que representa ese trabajo.

Comentarios

El método Run proporciona un conjunto de sobrecargas que facilitan el inicio de una tarea mediante valores predeterminados. Es una alternativa ligera a las sobrecargas de StartNew.

Run(Func<Task>, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para la tarea devuelta por function. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

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

Parámetros

function
Func<Task>

Trabajo que se va a ejecutar de forma asincrónica.

cancellationToken
CancellationToken

Token de cancelación que se puede usar para cancelar el trabajo si aún no se ha iniciado. Run(Func<Task>, CancellationToken) no pasa cancellationToken a action.

Devoluciones

Tarea que representa un proxy para la tarea devuelta por function.

Excepciones

El parámetro function se null.

La tarea se ha cancelado. Esta excepción se almacena en la tarea devuelta.

Se ha eliminado el CancellationTokenSource asociado a cancellationToken.

La tarea se ha cancelado.

Comentarios

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

Run(Action, CancellationToken)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task que representa ese trabajo. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

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

Parámetros

action
Action

Trabajo que se va a ejecutar de forma asincrónica.

cancellationToken
CancellationToken

Token de cancelación que se puede usar para cancelar el trabajo si aún no se ha iniciado. Run(Action, CancellationToken) no pasa cancellationToken a action.

Devoluciones

Tarea que representa el trabajo en cola que se va a ejecutar en el grupo de subprocesos.

Excepciones

El parámetro action se null.

La tarea se ha cancelado. Esta excepción se almacena en la tarea devuelta.

Se ha eliminado el CancellationTokenSource asociado a cancellationToken.

La tarea se ha cancelado.

Ejemplos

En el ejemplo siguiente se llama al método Run(Action, CancellationToken) para crear una tarea que itera los archivos en el directorio C:\Windows\System32. La expresión lambda llama al método Parallel.ForEach para agregar información sobre cada archivo a un objeto List<T>. Cada tarea anidada desasociada invocada por el bucle Parallel.ForEach comprueba el estado del token de cancelación y, si se solicita la cancelación, llama al método CancellationToken.ThrowIfCancellationRequested. El método CancellationToken.ThrowIfCancellationRequested produce una excepción de OperationCanceledException que se controla en un bloque de catch cuando el subproceso que realiza la llamada llama al método Task.Wait.

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

Comentarios

Si se solicita cancelación antes de que la tarea comience a ejecutarse, la tarea no se ejecuta. En su lugar, se establece en el estado Canceled y produce una excepción de TaskCanceledException.

El método Run(Action, CancellationToken) es una alternativa más sencilla al método TaskFactory.StartNew(Action, CancellationToken). Crea una tarea con los siguientes valores predeterminados:

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

Run(Func<Task>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para la tarea devuelta por 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);
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

Parámetros

function
Func<Task>

Trabajo que se va a ejecutar de forma asincrónica.

Devoluciones

Tarea que representa un proxy para la tarea devuelta por function.

Excepciones

El parámetro function se null.

Comentarios

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

Run(Action)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task que representa ese trabajo.

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

Parámetros

action
Action

Trabajo que se va a ejecutar de forma asincrónica.

Devoluciones

Tarea que representa el trabajo en cola que se va a ejecutar en ThreadPool.

Excepciones

El parámetro action se null.

Ejemplos

En el ejemplo siguiente se define un método ShowThreadInfo que muestra el Thread.ManagedThreadId del subproceso actual. Se llama directamente desde el subproceso de la aplicación y se llama desde el delegado Action pasado al método Run(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

El ejemplo siguiente es similar al anterior, salvo que usa una expresión lambda para definir el código que se va a ejecutar la tarea.

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

Los ejemplos muestran que la tarea asincrónica se ejecuta en un subproceso diferente del subproceso de aplicación principal.

La llamada al método Wait garantiza que la tarea se complete y muestre su salida antes de que finalice la aplicación. De lo contrario, es posible que el método Main se complete antes de que finalice la tarea.

En el ejemplo siguiente se muestra el método Run(Action). Define una matriz de nombres de directorio e inicia una tarea independiente para recuperar los nombres de archivo en cada directorio. Todas las tareas escriben los nombres de archivo en un solo objeto ConcurrentBag<T>. A continuación, el ejemplo llama al método WaitAll(Task[]) para asegurarse de que todas las tareas se han completado y, a continuación, muestra un recuento del número total de nombres de archivo escritos en el objeto 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

Comentarios

El método Run permite crear y ejecutar una tarea en una sola llamada de método y es una alternativa más sencilla al método StartNew. Crea una tarea con los siguientes valores predeterminados:

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

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

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para el Task(TResult) devuelto por function. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

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)

Parámetros de tipo

TResult

Tipo del resultado devuelto por la tarea de proxy.

Parámetros

function
Func<Task<TResult>>

Trabajo que se va a ejecutar de forma asincrónica.

Devoluciones

Un Task(TResult) que representa un proxy para el Task(TResult) devuelto por function.

Excepciones

El parámetro function se null.

Comentarios

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

Run<TResult>(Func<TResult>)

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task<TResult> que representa ese trabajo. Un token de cancelación permite cancelar el trabajo si aún no se ha iniciado.

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)

Parámetros de tipo

TResult

Tipo de valor devuelto de la tarea.

Parámetros

function
Func<TResult>

Trabajo que se va a ejecutar de forma asincrónica.

Devoluciones

Objeto de tarea que representa el trabajo en cola que se va a ejecutar en el grupo de subprocesos.

Excepciones

El parámetro function es null.

Ejemplos

En el ejemplo siguiente se cuenta el número aproximado de palabras en archivos de texto que representan libros publicados. Cada tarea es responsable de abrir un archivo, leer todo su contenido de forma asincrónica y calcular el recuento de palabras mediante una expresión regular. Se llama al método WaitAll(Task[]) para asegurarse de que todas las tareas se hayan completado antes de mostrar el recuento de palabras de cada libro en la consola.

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

La expresión regular \p{P}*\s+ coincide con cero, uno o más caracteres de puntuación seguidos de uno o varios caracteres de espacio en blanco. Se supone que el número total de coincidencias es igual al recuento aproximado de palabras.

Comentarios

El método Run es una alternativa más sencilla al método TaskFactory.StartNew(Action). Crea una tarea con los siguientes valores predeterminados:

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

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

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un proxy para el Task(TResult) devuelto por function.

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)

Parámetros de tipo

TResult

Tipo del resultado devuelto por la tarea de proxy.

Parámetros

function
Func<Task<TResult>>

Trabajo que se va a ejecutar de forma asincrónica.

cancellationToken
CancellationToken

Token de cancelación que se puede usar para cancelar el trabajo si aún no se ha iniciado. Run<TResult>(Func<Task<TResult>>, CancellationToken) no pasa cancellationToken a action.

Devoluciones

Un Task(TResult) que representa un proxy para el Task(TResult) devuelto por function.

Excepciones

El parámetro function se null.

La tarea se ha cancelado. Esta excepción se almacena en la tarea devuelta.

Se ha eliminado el CancellationTokenSource asociado a cancellationToken.

La tarea se ha cancelado.

Comentarios

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a

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

Source:
Task.cs
Source:
Task.cs
Source:
Task.cs

Pone en cola el trabajo especificado para ejecutarse en el grupo de subprocesos y devuelve un objeto Task(TResult) que representa ese trabajo.

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)

Parámetros de tipo

TResult

Tipo de resultado de la tarea.

Parámetros

function
Func<TResult>

Trabajo que se va a ejecutar de forma asincrónica.

cancellationToken
CancellationToken

Token de cancelación que se puede usar para cancelar el trabajo si aún no se ha iniciado. Run<TResult>(Func<TResult>, CancellationToken) no pasa cancellationToken a action.

Devoluciones

Un Task(TResult) que representa el trabajo en cola para ejecutarse en el grupo de subprocesos.

Excepciones

El parámetro function es null.

La tarea se ha cancelado. Esta excepción se almacena en la tarea devuelta.

Se ha eliminado el CancellationTokenSource asociado a cancellationToken.

La tarea se ha cancelado.

Ejemplos

En el ejemplo siguiente se crean 20 tareas que se repetirán hasta que un contador se incremente a un valor de 2 millones. Cuando las primeras 10 tareas alcanzan 2 millones, se cancela el token de cancelación y se cancelan las tareas cuyos contadores no han alcanzado los 2 millones. En el ejemplo se muestra la salida posible.

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

En lugar de usar la propiedad InnerExceptions para examinar excepciones, el ejemplo recorre en iteración todas las tareas para determinar qué se han completado correctamente y cuáles se han cancelado. Para aquellos que se han completado, muestra el valor devuelto por la tarea.

Dado que la cancelación es cooperativa, cada tarea puede decidir cómo responder a la cancelación. El ejemplo siguiente es como el primero, salvo que, una vez cancelado el token, las tareas devuelven el número de iteraciones que han completado en lugar de iniciar una excepción.

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

El ejemplo todavía debe controlar la excepción AggregateException, ya que las tareas que no se han iniciado cuando se solicita la cancelación siguen produciendo una excepción.

Comentarios

Si se solicita cancelación antes de que la tarea comience a ejecutarse, la tarea no se ejecuta. En su lugar, se establece en el estado Canceled y produce una excepción de TaskCanceledException.

El método Run es una alternativa más sencilla al método StartNew. Crea una tarea con los siguientes valores predeterminados:

Para obtener información sobre cómo controlar las excepciones producidas por las operaciones de tareas, vea control de excepciones.

Consulte también

Se aplica a