Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between Monitor and Lock in C#?
Both Monitor and lock provides a mechanism that synchronizes access to objects. lock is the shortcut for Monitor.Enter with try and finally.
Lock is a shortcut and it's the option for the basic usage. If we need more control to implement advanced multithreading solutions using TryEnter() Wait(), Pulse(), & PulseAll() methods, then the Montior class is your option.
Example for Lock −
Example
class Program{
static object _lock = new object();
static int Total;
public static void Main(){
AddOneHundredLock();
Console.ReadLine();
}
public static void AddOneHundredLock(){
for (int i = 1; i <= 100; i++){
lock (_lock){
Total++;
}
}
}
Example for Monitor −
Example
class Program{
static object _lock = new object();
static int Total;
public static void Main(){
AddOneHundredMonitor();
Console.ReadLine();
}
public static void AddOneHundredMonitor(){
for (int i = 1; i <= 100; i++){
Monitor.Enter(_lock);
try{
Total++;
}
finally{
Monitor.Exit(_lock);
}
}
}
}Advertisements