Synchronized(ArrayList)方法用于获取已同步(线程安全)的ArrayList包装器。
句法:
public static System.Collections.ArrayList Synchronized (System.Collections.ArrayList list);
在此,列表是要同步的ArrayList。
返回值:返回一个已同步的ArrayList包装器(线程安全)。
异常:如果列表为null,则此方法将引发ArgumentNullException。
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to check if ArrayList
// Is Synchronized or not
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating an ArrayList
ArrayList myList = new ArrayList();
// Adding elements to ArrayList
myList.Add("Geeks");
myList.Add("for");
myList.Add("Geeks");
myList.Add("Noida");
myList.Add("Geeks Classes");
myList.Add("Delhi");
// Creates a synchronized
// wrapper around the ArrayList
ArrayList smyList = ArrayList.Synchronized(myList);
// Displays the synchronization
// status of both ArrayList
Console.WriteLine("myList is {0}.", myList.IsSynchronized ?
"Synchronized" : "Not Synchronized");
Console.WriteLine("smyList is {0}.", smyList.IsSynchronized ?
"Synchronized" : "Not Synchronized");
}
}
输出:
myList is Not Synchronized.
smyList is Synchronized.
范例2:
// C# code to check if ArrayList
// Is Synchronized or not
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating an ArrayList
ArrayList myList = new ArrayList();
// Adding elements to ArrayList
myList.Add("Geeks");
myList.Add("for");
myList.Add("Geeks");
myList.Add("Noida");
myList.Add("Geeks Classes");
myList.Add("Delhi");
// it will give error as
// the parameter is null
ArrayList smyList = ArrayList.Synchronized(null);
}
}
运行时错误:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: list
注意:为了ArrayList的线程安全,所有操作都必须通过此包装器完成。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.arraylist.synchronized?view=netframework-4.7.2#System_Collections_ArrayList_Synchronized_System_Collections_ArrayList_