ActionBlock<TInput> Clase

Definición

Proporciona un bloque de flujo de datos que invoca un delegado proporcionado Action<T> para cada elemento de datos recibido.

generic <typename TInput>
public ref class ActionBlock sealed : System::Threading::Tasks::Dataflow::ITargetBlock<TInput>
public sealed class ActionBlock<TInput> : System.Threading.Tasks.Dataflow.ITargetBlock<TInput>
type ActionBlock<'Input> = class
    interface ITargetBlock<'Input>
    interface IDataflowBlock
type ActionBlock<'Input> = class
    interface IDataflowBlock
    interface ITargetBlock<'Input>
Public NotInheritable Class ActionBlock(Of TInput)
Implements ITargetBlock(Of TInput)

Parámetros de tipo

TInput

Tipo de datos en los que funciona.ActionBlock<TInput>

Herencia
ActionBlock<TInput>
Implementaciones

Ejemplos

En el ejemplo siguiente se muestra el uso de la ActionBlock<TInput> clase para realizar varios cálculos mediante bloques de flujo de datos y se devuelve el tiempo transcurrido necesario para realizar los cálculos. Este ejemplo de código forma parte de un ejemplo más grande proporcionado para el artículo How to: Specify the Degree of Parallelism in a Dataflow Block (Cómo: Especificar el grado de paralelismo en un bloque de flujo de datos ).

// Performs several computations by using dataflow and returns the elapsed
// time required to perform the computations.
static TimeSpan TimeDataflowComputations(int maxDegreeOfParallelism,
   int messageCount)
{
   // Create an ActionBlock<int> that performs some work.
   var workerBlock = new ActionBlock<int>(
      // Simulate work by suspending the current thread.
      millisecondsTimeout => Thread.Sleep(millisecondsTimeout),
      // Specify a maximum degree of parallelism.
      new ExecutionDataflowBlockOptions
      {
         MaxDegreeOfParallelism = maxDegreeOfParallelism
      });

   // Compute the time that it takes for several messages to
   // flow through the dataflow block.

   Stopwatch stopwatch = new Stopwatch();
   stopwatch.Start();

   for (int i = 0; i < messageCount; i++)
   {
      workerBlock.Post(1000);
   }
   workerBlock.Complete();

   // Wait for all messages to propagate through the network.
   workerBlock.Completion.Wait();

   // Stop the timer and return the elapsed number of milliseconds.
   stopwatch.Stop();
   return stopwatch.Elapsed;
}
' Demonstrates how to specify the maximum degree of parallelism 
' when using dataflow.
Friend Class Program
   ' Performs several computations by using dataflow and returns the elapsed
   ' time required to perform the computations.
   Private Shared Function TimeDataflowComputations(ByVal maxDegreeOfParallelism As Integer, ByVal messageCount As Integer) As TimeSpan
      ' Create an ActionBlock<int> that performs some work.
      Dim workerBlock = New ActionBlock(Of Integer)(Function(millisecondsTimeout) Pause(millisecondsTimeout), New ExecutionDataflowBlockOptions() With { .MaxDegreeOfParallelism = maxDegreeOfParallelism})
         ' Simulate work by suspending the current thread.
         ' Specify a maximum degree of parallelism.

      ' Compute the time that it takes for several messages to 
      ' flow through the dataflow block.

      Dim stopwatch As New Stopwatch()
      stopwatch.Start()

      For i As Integer = 0 To messageCount - 1
         workerBlock.Post(1000)
      Next i
      workerBlock.Complete()

      ' Wait for all messages to propagate through the network.
      workerBlock.Completion.Wait()

      ' Stop the timer and return the elapsed number of milliseconds.
      stopwatch.Stop()
      Return stopwatch.Elapsed
   End Function

   Private Shared Function Pause(ByVal obj As Object)
      Thread.Sleep(obj)
      Return Nothing
   End Function

Comentarios

Note

La biblioteca TPL Dataflow (el espacio de nombres System.Threading.Tasks.Dataflow) no se distribuye con .NET. Para instalar el System.Threading.Tasks.Dataflow espacio de nombres en Visual Studio, abra su proyecto, elija Administrar paquetes NuGet en el menú Proyecto y busque en línea el paquete System.Threading.Tasks.Dataflow. Como otra opción, para instalarlo mediante la CLI de .NET Core, ejecute dotnet add package System.Threading.Tasks.Dataflow.

Constructores

Nombre Description
ActionBlock<TInput>(Action<TInput>, ExecutionDataflowBlockOptions)

Inicializa una nueva instancia de la ActionBlock<TInput> clase con las opciones de configuración y acción especificadas.

ActionBlock<TInput>(Action<TInput>)

Inicializa una nueva instancia de la ActionBlock<TInput> clase con la acción especificada.

ActionBlock<TInput>(Func<TInput,Task>, ExecutionDataflowBlockOptions)

Inicializa una nueva instancia de la ActionBlock<TInput> clase con las opciones de configuración y acción especificadas.

ActionBlock<TInput>(Func<TInput,Task>)

Inicializa una nueva instancia de la ActionBlock<TInput> clase con la acción especificada.

Propiedades

Nombre Description
Completion

Obtiene un Task objeto que representa la operación asincrónica y la finalización del bloque de flujo de datos.

InputCount

Obtiene el número de elementos de entrada que esperan ser procesados por este bloque.

Métodos

Nombre Description
Complete()

Indica al bloque de flujo de datos que no debe aceptar ni producir más mensajes y no debe consumir más mensajes pospuestos.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
Post(TInput)

Publica un elemento en el bloque de flujo de datos de destino.

ToString()

Devuelve una cadena que representa el nombre con formato de esta IDataflowBlock instancia.

Implementaciones de interfaz explícitas

Nombre Description
IDataflowBlock.Fault(Exception)

Hace que el bloque de flujo de datos se complete en un estado defectuoso.

ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader, TInput, ISourceBlock<TInput>, Boolean)

Ofrece un mensaje al bloque de flujo de datos y le ofrece la oportunidad de consumir o posponer el mensaje.

Métodos de extensión

Nombre Description
AsObserver<TInput>(ITargetBlock<TInput>)

Crea una nueva IObserver<T> abstracción sobre .ITargetBlock<TInput>

Post<TInput>(ITargetBlock<TInput>, TInput)

Publica un elemento en .ITargetBlock<TInput>

SendAsync<TInput>(ITargetBlock<TInput>, TInput, CancellationToken)

Ofrece de forma asincrónica un mensaje al bloque de mensajes de destino, lo que permite posponer.

SendAsync<TInput>(ITargetBlock<TInput>, TInput)

Ofrece de forma asincrónica un mensaje al bloque de mensajes de destino, lo que permite posponer.

Se aplica a