📜  C#中的Stack.Synchronized()方法

📅  最后修改于: 2021-05-29 13:59:47             🧑  作者: Mango

此方法(位于System.Collections命名空间下)用于为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);
    }
}

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.synchronized?view=netframework-4.7.2