C#中的Queue.Synchronized()方法用于返回包装原始队列并且是线程安全的新Queue。
语法如下-
public static System.Collections.Queue Synchronized (System.Collections.Queue queue);
在上方,参数队列是要同步的队列。
现在让我们看一个例子-
using System; using System.Collections; public class Demo { public static void Main(){ Queue queue = new Queue(); queue.Enqueue("AB"); queue.Enqueue("BC"); queue.Enqueue("CD"); queue.Enqueue("DE"); queue.Enqueue("EF"); queue.Enqueue("FG"); queue.Enqueue("GH"); queue.Enqueue("HI"); Console.WriteLine("Queue..."); IEnumerator demoEnum = queue.GetEnumerator(); while (demoEnum.MoveNext()){ Console.WriteLine(demoEnum.Current); } Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized); Queue queue2 = Queue.Synchronized(queue); Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized); } }
输出结果
这将产生以下输出-
Queue... AB BC CD DE EF FG GH HI Is Queue synchronized? = False Is Queue synchronized now? = True
现在让我们来看另一个示例-
using System; using System.Collections; public class Demo { public static void Main(){ Queue queue = new Queue(); queue.Enqueue(100); queue.Enqueue(200); queue.Enqueue(300); Console.WriteLine("Is Queue synchronized? = "+queue.IsSynchronized); Queue queue2 = Queue.Synchronized(queue); Console.WriteLine("Is Queue synchronized now? = "+queue2.IsSynchronized); Console.Write("Count of elements = "); Console.WriteLine(queue.Count); Console.WriteLine("Queue..."); foreach(int i in queue){ Console.WriteLine(i); } Console.WriteLine("Does the queue has element 500? = "+queue.Contains(500)); int[] intArr = new int[5]; intArr[0] = 1; intArr[1] = 2; intArr[2] = 3; intArr[3] = 4; queue.CopyTo(intArr, 1); Console.WriteLine("\nQueue (Updated)"); foreach(int i in queue){ Console.WriteLine(i); } Console.WriteLine("\nArray (Updated)"); foreach(int i in intArr){ Console.WriteLine(i); } } }
输出结果
这将产生以下输出-
Is Queue synchronized? = False Is Queue synchronized now? = True Count of elements = 3 Queue... 100 200 300 Does the queue has element 500? = False Queue (Updated) 100 200 300 Array (Updated) 1 100 200 300 0