相应的并发队列

Concurrent queue dequeue

我正在使用并发队列并通过创建操作委托通过多个线程从队列中取出数据

Action action = () =>
        {
            SubscriptionResponseModel subsModel;
            while (concurrentQueue.TryTake(out subsModel))
            {
                MakeTransactionAndAddIntoQueue(subsModel);
            }
        };

并调用此操作委托并行多个线程

Parallel.Invoke(action, action, action, action, action, action, action, action, action, action, action, action, action, action, action);

我想知道一件事,当我在多个操作中使用SubscriptionResponseModel subsModel;时,它是线程安全的吗?

action 的每次调用都会有自己的 subsModel - 因此使用它从队列中获取值是线程安全的。

线程不安全的情况是当您从外部上下文捕获变量时:

    // ********** Code showing non-thread safe case **************
    SubscriptionResponseModel subsModel;
    Action action = () =>
    {
        // all invocations of `action` will share subsModel as it is captured.
        while (concurrentQueue.TryDequeue(out subsModel))
        {
            MakeTransactionAndAddIntoQueue(subsModel);
        }
    };

备注:

  • 使用 SubscriptionResponseModel 的 properties/methods 是否线程安全取决于该类型。
  • 很有可能 运行 多个 TryDequeue 并行根本不会提高性能。 Parallel.Invoke 的多个繁忙循环只会阻塞多个不断查询空队列的线程。