如何在 C# 中获取堆栈的同步访问权限?
若要获取堆栈的同步访问权限,请使用以下代码 -
示例
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("Count of elements = "+stack.Count); Console.WriteLine("Synchronize access..."); lock(stack.SyncRoot) { foreach(Object ob in stack) { Console.WriteLine(ob); } } } }
输出
这将产生以下输出 -
Stack... 500 400 300 200 100 Count of elements = 5 Synchronize access... 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("
Synchronize access..."); lock(stack.SyncRoot) { foreach(Object ob in stack) { Console.WriteLine(ob); } } } }
输出
这将产生以下输出 -
Stack... Justin Taylor Selena Katie Amy Tom Philips Tim Jacob Synchronize access... Justin Taylor Selena Katie Amy Tom Philips Tim Jacob
广告