此方法(位于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
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.synchronized?view=netframework-4.7.2