- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get Synchronize access to an Array in C#?
To get synchronize access to an array, the code is as follows −
Example
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); } } }
Output
This will produce the following output −
Integer array... 5 10 15 20 25 30 35 40 After applying lock on array... 5 10 15 20 25 30 35 40
Example
Let us see another example −
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); } } }
Output
This will produce the following output −
String array... Harry Tom Kevin Ryan Katie Amy After applying lock on array... Harry Tom Kevin Ryan Katie Amy
Advertisements