ConcurrentQueue<> 中的 TryDequeue 和 TryTake 有什么区别?

Bar*_*chs 4 .net c# concurrency producer-consumer concurrent-queue

在类中,定义了ConcurrentQeueue<>额外的方法。TryDequeue()但是,当它实现时IProducerConsumerCollection<>,它也有一个TryTake()方法。根据文档,他们都做同样的事情:

尝试出队

尝试删除并返回并发队列开头的对象。

尝试一下

对于 ConcurrentQueue,此操作将尝试从 ConcurrentQueue 的开头删除对象。

为什么要费心实施该TryDequeue方法呢?

Nko*_*osi 6

ConcurrentQueue<> 中的 TryDequeue 和 TryTake 有什么区别

TryTake根据可用的源代码,调用没有区别TryDequeue

/// <summary>
/// Attempts to remove and return an object from the <see cref="Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake([MaybeNullWhen(false)] out T item) => TryDequeue(out item);
Run Code Online (Sandbox Code Playgroud)

来源:https://source.dot.net/#System.Private.CoreLib/ConcurrentQueue.cs,201

为什么要费心实现 TryDequeue 方法呢?

TryDequeue遵循与队列相关的预期名称约定,并且是本地的ConcurrentQueue<>。同样,TryTake遵循通常与生产者/消费者模式相关的命名约定。