如何在 C# 中获取对数组的同步访问?
若要获取对数组的同步访问,代码如下 -
示例
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
广告