要获得对数组的同步访问,代码如下-
using System; public class Demo { public static void Main() { Array intArr = new int[] {5, 10, 15, 20, 25, 30, 35, 40 }; Console.WriteLine("Integer array..."); foreach (int i in intArr) Console.WriteLine(i); Console.WriteLine("After applying lock on array..."); lock(intArr.SyncRoot) { foreach (Object ob in intArr) Console.WriteLine(ob); } } }
输出结果
这将产生以下输出-
Integer array... 5 10 15 20 25 30 35 40 After applying lock on array... 5 10 15 20 25 30 35 40
让我们看另一个例子-
using System; public class Demo { public static void Main() { Array strArr = new String[] {"Harry", "Tom", "Kevin", "Ryan", "Katie", "Amy" }; Console.WriteLine("String array..."); foreach (string i in strArr) Console.WriteLine(i); Console.WriteLine("After applying lock on array..."); lock(strArr.SyncRoot) { foreach (Object ob in strArr) Console.WriteLine(ob); } } }
输出结果
这将产生以下输出-
String array... Harry Tom Kevin Ryan Katie Amy After applying lock on array... Harry Tom Kevin Ryan Katie Amy