C# ConcurrentQueue (线程安全)

http://dotnetpattern.com/csharp-concurrentqueue

Add Items in ConcurrentQueue
It provides an Enqueue method to add any item at the end of the queue. Enqueue takes the argument which data type matches with the type argument. Below is the example.

ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
coll.Enqueue(1);
coll.Enqueue(2);
coll.Enqueue(3);
coll.Enqueue(4);

It is only method available to add item to ConcurrentQueue. Enqueue method does not have any other overloaded methods.

Retrieve/Remove Single Item
For retrieving items, we have two methods.

TryPeek
TryDequeue
TryPeek Method
TryPeek method tries to get an item from the ConcurrentQueue without removing item from the list. It returns true if operation is successful otherwise returns false. It returns the item into an out parameter. Below is the example.

ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
coll.Enqueue(1);
coll.Enqueue(2);
coll.Enqueue(3);
coll.Enqueue(4);
 
int item;
bool isSuccessful = coll.TryPeek(out item);
Console.WriteLine(isSuccessful); //Returns True
Console.WriteLine(item);    //Return "1"

As TryPeek does not remove an item from the queue, it returns the same item again an again.

TryDequeue Method
TryDequeue method tries to get an item from the ConcurrentQueue, but it removes item from the list. It also returns true if operation is successful other returns false. It returns the item into an out parameter. Below is the example.

ConcurrentQueue<int> coll = new ConcurrentQueue<int>();
coll.Enqueue(1);
coll.Enqueue(2);
coll.Enqueue(3);
coll.Enqueue(4);
 
int item;
bool isSuccessful = coll.TryDequeue(out item);  
Console.WriteLine(isSuccessful); //Returns True
Console.WriteLine(item);    //Return "1"
 
isSuccessful = coll.TryDequeue(out item);
Console.WriteLine(isSuccessful); //Returns True
Console.WriteLine(item);    //Return "2"

In the above example, when we dequeue an item first time it returns “1” item in the out parameter. When we again use dequeue method, it returns the second item inserted in the queue that is “2”.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值