一个ActionBlock可以包含一个状态吗?

问题描述 投票:0回答:1

我正在编写使用TPL数据流的应用程序。我正在尝试配置一个动作块以写入数据库。

但是,我需要此操作块才能对收到的第一条消息执行初始化步骤(请注意,我必须等待第一条消息并且不能在创建操作块的过程中执行初始化操作。)>

因此,我的操作块需要保持某种状态,以指示其是否已经收到第一条消息。

ActionBlock是否可以维持状态?

请参考下面的Microsoft示例代码,如何将状态变量添加到ActionBlock?似乎它仅维护局部变量。

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

我正在编写使用TPL数据流的应用程序。我正在尝试配置一个动作块以写入数据库。但是,我需要此操作块才能对...

c# lambda task-parallel-library tpl-dataflow
1个回答
0
投票

您可以这样实现自己的StatefulActionBlock<T>。根据您的MaxDegreeOfParallelism,您可能不需要锁(即使这样做,也可能有实现线程安全性的更好方法)。

© www.soinside.com 2019 - 2024. All rights reserved.