ActionBlock<TInput> Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Fornece um bloco de fluxo de dados que invoca um delegado fornecido Action<T> para cada elemento de dados recebido.
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
Public NotInheritable Class ActionBlock(Of TInput)
Implements ITargetBlock(Of TInput)
Parâmetros de tipo
- TInput
O tipo de dados em que isso ActionBlock<TInput> opera.
- Herança
-
ActionBlock<TInput>
- Implementações
Exemplos
O exemplo a seguir mostra o uso da ActionBlock<TInput> classe para executar vários cálculos usando blocos de fluxo de dados e retorna o tempo decorrido necessário para executar os cálculos. Este exemplo de código faz parte de um exemplo maior fornecido para o artigo Como especificar o grau de paralelismo em um artigo do Bloco de Fluxo de Dados .
// 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
Comentários
Note
A Biblioteca de Fluxo de Dados TPL (o namespace System.Threading.Tasks.Dataflow) não é distribuída com .NET. Para instalar o namespace System.Threading.Tasks.Dataflow no Visual Studio, abra seu projeto, escolha Gerenciar Pacotes NuGet no menu do Projeto e pesquise online o pacote System.Threading.Tasks.Dataflow. Como alternativa, instale-o usando a CLI do .NET Core e execute dotnet add package System.Threading.Tasks.Dataflow.
Construtores
| Nome | Description |
|---|---|
| ActionBlock<TInput>(Action<TInput>, ExecutionDataflowBlockOptions) |
Inicializa uma nova instância da ActionBlock<TInput> classe com as opções de ação e configuração especificadas. |
| ActionBlock<TInput>(Action<TInput>) |
Inicializa uma nova instância da ActionBlock<TInput> classe com a ação especificada. |
| ActionBlock<TInput>(Func<TInput,Task>, ExecutionDataflowBlockOptions) |
Inicializa uma nova instância da ActionBlock<TInput> classe com as opções de ação e configuração especificadas. |
| ActionBlock<TInput>(Func<TInput,Task>) |
Inicializa uma nova instância da ActionBlock<TInput> classe com a ação especificada. |
Propriedades
| Nome | Description |
|---|---|
| Completion |
Obtém um Task objeto que representa a operação assíncrona e a conclusão do bloco de fluxo de dados. |
| InputCount |
Obtém o número de itens de entrada que estão aguardando para serem processados por esse bloco. |
Métodos
| Nome | Description |
|---|---|
| Complete() |
Sinaliza para o bloco de fluxo de dados que ele não deve aceitar nem produzir mais mensagens e não deve consumir mais mensagens adiadas. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| Post(TInput) |
Posta um item no bloco de fluxo de dados de destino. |
| ToString() |
Retorna uma cadeia de caracteres que representa o nome formatado dessa IDataflowBlock instância. |
Implantações explícitas de interface
| Nome | Description |
|---|---|
| IDataflowBlock.Fault(Exception) |
Faz com que o bloco de fluxo de dados seja concluído em um estado com falha. |
| ITargetBlock<TInput>.OfferMessage(DataflowMessageHeader, TInput, ISourceBlock<TInput>, Boolean) |
Oferece uma mensagem para o bloco de fluxo de dados e oferece a ele a oportunidade de consumir ou adiar a mensagem. |
Métodos de Extensão
| Nome | Description |
|---|---|
| AsObserver<TInput>(ITargetBlock<TInput>) |
Cria uma nova IObserver<T> abstração sobre o ITargetBlock<TInput>. |
| Post<TInput>(ITargetBlock<TInput>, TInput) |
Posta um item no ITargetBlock<TInput>. |
| SendAsync<TInput>(ITargetBlock<TInput>, TInput, CancellationToken) |
Oferece de forma assíncrona uma mensagem para o bloco de mensagens de destino, permitindo o adiamento. |
| SendAsync<TInput>(ITargetBlock<TInput>, TInput) |
Oferece de forma assíncrona uma mensagem para o bloco de mensagens de destino, permitindo o adiamento. |