message queue
Queue (System.Collections.Queue) represents a FIFO collection of objects. When you need access to the FIFO, then use the queue. When you add a list, called into the team , when you remove the item from the list, called a team . Objects stored in a Queue (queue) is inserted at one end, is removed from the other end.
Method name | Note |
Void Clear() | From the Queue Remove all objects. |
Bool Contains(object obj) | Determine whether an element is in the Queue. |
Object Clone() | Creates a shallow copy of the Queue. |
Void CopyTo(Array array,int index) | Copy from the specified array index began Queue elements to an existing one-dimensional Array in. |
Object Dequeue() | Removes and returns the object at the beginning of the Queue. |
Void Enqueue(object obj) | Add the object to the end of the Queue. |
Object Peek() | Queue return the object is located at the beginning but do not remove it. |
Object[] ToArray() | Copy Queue elements to a new array. |
Void TrimToSize() | The capacity is set to the actual number of elements in the Queue. |
Sample code:
class Program { // definition of a message queue static Queue < String > QS = new new Queue < String > (); static the System.Threading.Timer Timer; // process the data in the message queue Private static void toDoData ( Object State) { List < String > = qsList new new List < String > (); IF (qs.Count> 0 ) { the while ( to true ) { String Item = null ; the try { // according to the FIFO principle, removing the data queue
// If when calling the Dequeue () method, there are no more elements in the queue, it throws an exception InvalidOperationException type. It is necessary to try-catch capture abnormal Item = qs.Dequeue (); } the catch { } IF (Item =! Null ) { qsList.Add (Item); } the else { BREAK ; } } // print out the data of each treatment String doResultStr = String .join ( " , " , qsList); Console.WriteLine (doResultStr + " \ n- " ); IF (doResultStr.Contains ( " 101 " )) { // Timeout.Infinite great, the execution time interval timer is set to infinity, which is equivalent to temporarily use a timer. timer.Change ( . 1 , Timeout.Infinite); } } } static void the Main ( String [] args) { // every second queue execution removing Timer = new new the Timer (toDoData, null , 1000 , 1000 ); ProductData (); ; the Console.ReadKey () } // callback returned continuously and constantly returning analog data (now facing data) Private static void ProductData () { for ( int I = 0 ; I < 10000 ; I ++ ) { the Thread.Sleep ( 200 is ); // add data to the end of the queue qs.Enqueue (String .Format (" This is the first data {0} " , I)); } } }
Dequeue former method performed: queue contains data Article 22
After Dequeue method of performing: a queue of data removed 22
data item is removed, developers to easily operate it
Execution results are as follows: