Поделиться через


ActionBlock<TInput>.Completion Свойство

Определение

Task Возвращает объект, представляющий асинхронную операцию и завершение блока потока данных.

public:
 property System::Threading::Tasks::Task ^ Completion { System::Threading::Tasks::Task ^ get(); };
public System.Threading.Tasks.Task Completion { get; }
member this.Completion : System.Threading.Tasks.Task
Public ReadOnly Property Completion As Task

Значение свойства

Завершенная задача.

Реализации

Примеры

В следующем примере показано, как использовать Completion свойство для ожидания распространения всех сообщений по сети. Этот пример кода является частью более крупного примера, предоставленного в разделе "Практическое руководство. Указание степени параллелизма в разделе блока потока данных ".

// 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

Комментарии

Блок потока данных считается завершенным, если он в настоящее время не обрабатывает сообщение, и когда он гарантирует, что он больше не будет обрабатывать сообщения. Возвращенное Task состояние перейдет в завершенное состояние после завершения связанного блока. Он перейдет в RanToCompletion состояние, когда блок успешно завершает обработку в соответствии с определенной семантикой блока данных. Он перейдет Faulted в состояние, когда блок потока данных завершил обработку преждевременно из-за необработанного исключения, и он перейдет в Canceled состояние, когда блок потока данных завершил обработку преждевременно после получения запроса на отмену. Если задача завершается в Faulted состоянии, его Exception свойство возвращает AggregateException исключение, содержащее одно или несколько исключений, которые привели к сбою блока.

Применяется к