SortedList.Synchronized(SortedList)方法用于获取SortedList对象的同步(线程安全)包装。
句法:
public static System.Collections.SortedList Synchronized (System.Collections.SortedList list);
在此, list是要同步的SortedList对象的名称。
异常:如果列表为null,则此方法将引发ArgumentNullException
下面的程序说明了上面讨论的方法的使用:
范例1:
// C# code to create a synchronized
// (thread-safe) wrapper for a
// SortedList object
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating an SortedList
SortedList mySortedList = new SortedList();
// Adding elements to SortedList
mySortedList.Add("1", "one");
mySortedList.Add("2", "two");
mySortedList.Add("3", "three");
mySortedList.Add("4", "four");
mySortedList.Add("5", "five");
// Creating a synchronized wrapper
// around the SortedList.
SortedList mySortedList_1 =
SortedList.Synchronized(mySortedList);
// --------- Using IsSynchronized Property
// print the status of both SortedList
Console.WriteLine("mySortedList SortedList is {0}.",
mySortedList.IsSynchronized ? "synchronized" :
"not synchronized");
Console.WriteLine("mySortedList_1 SortedList is {0}.",
mySortedList_1.IsSynchronized ? "synchronized" :
"not synchronized");
}
}
输出:
mySortedList SortedList is not synchronized.
mySortedList_1 SortedList is synchronized.
范例2:
// C# code to create a synchronized
// (thread-safe) wrapper for a
// SortedList object
using System;
using System.Collections;
class GFG {
// Driver code
public static void Main()
{
// Creating an SortedList
SortedList mySortedList = new SortedList();
// Adding elements in SortedList
mylist.Add("4", "Even");
mylist.Add("9", "Odd");
mylist.Add("5", "Odd and Prime");
mylist.Add("2", "Even and Prime");
// it will give runtime error as
// table parameter can't be null
SortedList my2 = SortedList.Synchronized(null);
}
}
运行时错误:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: list
注意:为了确保SortedList对象的线程安全,所有操作必须仅通过此包装器完成。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.sortedlist.synchronized?view=netframework-4.7.2