如何在 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

更新於: 2019 年 12 月 16 日

68 次瀏覽

開啟你的 職業 生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.