c# - 适当使用 BlockingCollection

标签 c# .net multithreading task-parallel-library

我即将使用如下所示的 BlockingCollection,只是想检查它是否适合线程安全等。想知道我是否需要 CancellationTokenSource。

谢谢

public class MyApp
{
  private BlockingCollection<int> blockingCollection;

  public void Start()
  {
     blockingCollection= new BlockingCollection<int>();
     var task = Task.Factory.StartNew(ProcessData);
  }

  public void Add(int value)
  {
    blockingCollection.Add(value); //This is a thread that receives input
  }

  private void ProcessData()
  {
    foreach(var item in blockingCollection.GetConsumingEnumerable())
    {  
      ...
    }
  }

  public void Finish()
  {
    blockingCollection.CompleteAdding();
  }
}

最佳答案

显然,您可以在代码中使用取消 token 来支持优雅的取消模式:

  private readonly CancellationTokenSource cts = new CancellationTokenSource();

  public void Start()
  {
     blockingCollection= new BlockingCollection<int>();
     var task = Task.Factory.StartNew(ProcessData, cts.Token);
  }

  private void ProcessData()
  {
    foreach(var item in blockingCollection.GetConsumingEnumerable(cts.Token))
    {  
        cts.Token.ThrowIfCancellationRequested();

        // ...
    }
  }

  public void Cancel()
  {
      cts.Cancel();
  }

关于c# - 适当使用 BlockingCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12601966/

相关文章:

python - 无法在Python中同时运行线程

ios - 如何检查调度队列是否为空?

java - 处理 Java ExecutorService 任务的异常

c# - 命名空间 'OracleClient' 中不存在类型或命名空间名称 'System.Data'

.net - 自定义服务器控制导致 UpdatePanel 内的完整回发

c# - .NET Entity Framework 核心

.net - 如何允许使用 XslCompiledTransform (.NET) 通过 XSLT 的 document(uri) 函数加载 XML 文档中的 DTD

c# - 无法连接到 .Net 中的 SQL Server 2008

c# - 如何在自定义用户控件(.Net 4、Winforms)上使用项目集合编辑器?

c# - HtmlGenericControl 和 id