Instructor-led online courses in ASP.NET Core, ASP.NET MVC, and ASP.NET Design Patterns. Read more...
Instructor-led online courses in ASP.NET Core, ASP.NET MVC, and ASP.NET Design Patterns. Conducted by Bipin Joshi on weekends. More details are available here.

Using Monitor Class For Thread Synchronization


While developing a multithreaded application it is very important to maintain synchronization between multiple calls to the same method. Consider for example that you have a function that writes to a file. If at the same time multiple threads call this function it is bound to throw an exception as previous method call is yet to finish with the file. To avoid such situations you can use Monitor class.

Namespaces Involved

Following namespaces are involved in our example:
  • System
  • System.Threading
  • System.IO
  • System.Text

Using Monitor class

Monitor class can synchronize method calls using its Enter and Exit methods. Following code shows how these methods work:
Dim fs As FileStream = New FileStream
("C:\Temp\SyncTest.txt", FileMode.Append)
Dim t As Thread = Thread.CurrentThread
fs.Write(Encoding.ASCII.GetBytes(t.Name & vbCrLf), 
0, t.Name.Length + 2)
Dim i As Integer
For i = 0 To 10000
   fs.Write(Encoding.ASCII.GetBytes(i & ","),
   0, i.ToString().Length + 1)
Here, we called Monitor.Enter method at the start of the method followed by our code that writes into a file. Once the writing operation is complete we call Monitor.Exit method. This ensures that till the time one thread is executing the function any other thread can not execute the same function. You can easily check what happens if you do not use Monitor class by simply commenting these two lines.

Bipin Joshi is a software consultant, trainer, author and spiritual yoga mentor having 23+ years of experience in software development. He teaches online training courses in ASP.NET Core, ASP.NET MVC, and Design Patterns to individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 02 November 2002

Tags : .NET Framework VB.NET C# Components Multithreading

Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.