.net 并发队列中的TryDequeue和TryTake < >之间有什么区别?

ehxuflar  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(120)

ConcurrentQeueue<>类中,定义了额外的方法TryDequeue()。但是,由于它实现了IProducerConsumerCollection<>,因此它也有一个TryTake()方法。根据文档,它们都做同样的事情:
TryDequeue
尝试移除并返回并发队列开头的对象。
TryTake:
对于ConcurrentQueue,此操作将尝试从ConcurrentQueue的开头删除对象。
为什么要实现TryDequeue方法呢?

juud5qan

juud5qan1#

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);

字符串
来源:https://source.dot.net/#System.Private. CoreLib/ConcurrentQueue.cs,201
为什么要费心实现TryDequeue方法呢?
TryDequeue遵循与队列相关联的预期名称约定,并且是ConcurrentQueue<>本地的。同样,TryTake遵循通常与生产者/消费者模式相关联的命名约定。

相关问题