ConcurrentQueue<T>.TryDequeue(T) 方法


尝试移除并返回位于并发队列开头处的对象。Tries to remove and return the object at the beginning of the concurrent queue.

 bool TryDequeue([Runtime::InteropServices::Out] T % result);
public bool TryDequeue (out T result);
member this.TryDequeue : 'T -> bool
Public Function TryDequeue (ByRef result As T) As Boolean



此方法返回时,如果操作成功,则 result 包含所移除的对象。When this method returns, if the operation was successful, result contains the object removed. 如果没有可供移除的对象,则不指定该值。If no object was available to be removed, the value is unspecified.


如果成功在 ConcurrentQueue<T> 开头处移除并返回了元素,则为 true;否则为 falsetrue if an element was removed and returned from the beginning of the ConcurrentQueue<T> successfully; otherwise, false.


ConcurrentQueue<T> 在内部处理所有同步。ConcurrentQueue<T> handles all synchronization internally. 如果两个线程正好在同一时间调用 TryDequeue,则不会阻止任一操作。If two threads call TryDequeue at precisely the same moment, neither operation is blocked. 如果在两个线程之间检测到冲突,则一个线程必须再次尝试检索下一元素,并且将内部处理同步。When a conflict is detected between two threads, one thread has to try again to retrieve the next element, and the synchronization is handled internally.

TryDequeue 尝试从队列中删除元素。TryDequeue tries to remove an element from the queue. 如果此方法成功,则将删除该项,并且此方法将返回 true;否则将返回 falseIf the method is successful, the item is removed and the method returns true; otherwise, it returns false. 对于队列中的其他操作而言,这将以原子方式发生。That happens atomically with respect to other operations on the queue. 如果队列是使用代码(如 q.Enqueue("a"); q.Enqueue("b"); q.Enqueue("c");)填充的,并且两个线程同时尝试取消元素排队,则一个线程将取消 a 排队,而另一个线程将取消 b 排队。If the queue was populated with code such as q.Enqueue("a"); q.Enqueue("b"); q.Enqueue("c"); and two threads concurrently try to dequeue an element, one thread will dequeue a and the other thread will dequeue b. TryDequeue 的两个调用均将返回 true,因为它们都能取消元素排队。Both calls to TryDequeue will return true, because they were both able to dequeue an element. 如果每个线程都返回取消附加元素排队,则一个线程将取消 c 排队并返回 true,而另一个线程将发现队列为空并返回 falseIf each thread goes back to dequeue an additional element, one of the threads will dequeue c and return true, whereas the other thread will find the queue empty and will return false.