스택에 대한 동기화 액세스를 얻으려면 코드는 다음과 같습니다. -
예
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("\nSynchronize 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