要获得对堆栈的同步访问,代码如下-
using System; using System.Collections; public class Demo { public static void Main() { Stack stack = new Stack(); stack.Push(100); stack.Push(200); stack.Push(300); stack.Push(400); stack.Push(500); Console.WriteLine("Stack..."); foreach(Object ob in stack) { Console.WriteLine(ob); } Console.WriteLine("元素数 = "+stack.Count); Console.WriteLine("同步访问..."); lock(stack.SyncRoot) { foreach(Object ob in stack) { Console.WriteLine(ob); } } } }
输出结果
这将产生以下输出-
Stack... 500 400 300 200 100 元素数 = 5 同步访问... 500 400 300 200 100
现在让我们来看另一个示例-
using System; using System.Collections; public class Demo { public static void Main() { Stack stack = new Stack(); stack.Push("Jacob"); stack.Push("Tim"); stack.Push("Philips"); stack.Push("Tom"); stack.Push("Amy"); stack.Push("Katie"); stack.Push("Selena"); stack.Push("Taylor"); stack.Push("Justin"); Console.WriteLine("Stack..."); foreach(Object ob in stack) { Console.WriteLine(ob); } Console.WriteLine("\nSynchronize access..."); lock(stack.SyncRoot) { foreach(Object ob in stack) { Console.WriteLine(ob); } } } }
输出结果
这将产生以下输出-
Stack... Justin Taylor Selena Katie Amy Tom Philips Tim Jacob 同步访问... Justin Taylor Selena Katie Amy Tom Philips Tim Jacob