當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Stack.Synchronized()用法及代碼示例

此方法(位於System.Collections命名空間下)用於為Stack返回一個同步的(線程安全的)包裝器。為了保證堆棧的線程安全,所有操作都必須通過此包裝器完成。

用法:

public static System.Collections.Stack Synchronized (System.Collections.Stack stack);



返回值:它返回圍繞堆棧的同步包裝器。

異常:如果堆棧為null,則此方法將提供ArgumentNullException。

以下示例程序旨在說明上述方法的使用:

示例1:

// C# code to illustrate the 
// Stack.Synchronized() Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Stack 
        Stack myStack = new Stack(); 
  
        // Inserting the elements into the Stack 
        myStack.Push("Geeks"); 
        myStack.Push("Geeks Classes"); 
        myStack.Push("Noida"); 
        myStack.Push("Data Structures"); 
        myStack.Push("GeeksforGeeks"); 
  
        // Creates a synchronized 
        // wrapper around the Stack 
        Stack st = Stack.Synchronized(myStack); 
  
        // Displays the synchronization 
        // status of both Stack 
        Console.WriteLine("myStack is {0}.", myStack.IsSynchronized ? 
                                "Synchronized" : "Not Synchronized"); 
  
        Console.WriteLine("st is {0}.", st.IsSynchronized ?  
                      "Synchronized" : "Not Synchronized"); 
    } 
}

輸出:

myStack is Not Synchronized.
st is Synchronized.

示例2:

// C# code to illustrate the 
// Stack.Synchronized() Method 
using System; 
using System.Collections; 
  
class GFG { 
  
    // Driver code 
    public static void Main() 
    { 
  
        // Creating a Stack 
        Stack myStack = new Stack(); 
  
        // Inserting the elements into the Stack 
        myStack.Push("C"); 
        myStack.Push("C++"); 
        myStack.Push("Java"); 
        myStack.Push("C#"); 
        myStack.Push("Python"); 
  
        // it will give error as 
        // the parameter is null 
        Stack sq = Stack.Synchronized(null); 
    } 
}

運行時錯誤:

Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: stack

參考:



相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Stack.Synchronized() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。