Enumerating through collections is inherently not a thread-safe process. Even when the collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To ensure thread safety during enumeration, you can lock the collection during the entire enumeration, or catch exceptions that are thrown due to changes made by other threads.
The following examples show how to synchronize the queue, how to determine whether the queue is synchronized, and how to use synchronized queue. Unity3d Tutorial Manual
Using System;
Using System.Collections;
public class Samplesqueue {public
static void Main () {
//creates and initializes a new Queue.
Queue Myq = new Queue ();
Myq.enqueue ("the");
Myq.enqueue ("quick");
Myq.enqueue ("Brown");
Myq.enqueue ("Fox");
Creates a synchronized wrapper around the Queue.
Queue MYSYNCDQ = queue.synchronized (MYQ);
Displays the Sychronization status of both queues.
Console.WriteLine ("Myq is {0}.", myq.issynchronized?) "Synchronized": "Not Synchronized");
Console.WriteLine ("MYSYNCDQ is {0}.", mysyncdq.issynchronized?) "Synchronized": "Not Synchronized");
}
}
By contrasting the running results, it is obvious that the queue that is packaged through the Queue.synchronized method is synchronized, and no packaging is synchronized. You can declare this at the instantiation point,
Creates a synchronized wrapper around the Queue.
nbsp;
Queue MYSYNCDQ = queue.synchronized (new queue ());
This allows synchronization object locks in the queue to be used in a multithreaded environment to prevent multithreading from writing to the queue at the same time. If you want to make the queue object inaccessible to other threads, you can use Lock (queue) to do this.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/