Improve Your Technology

Just another blog for techology

Thread Synchronization

Using Monitor Class For Thread Synchronization

 

Introduction

 

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:

 

Monitor.Enter(Me)

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)

Next

fs.Close()

Monitor.Exit(Me)

 

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.

 

 

Using ThreadPool Class

 

Introduction

 

You can use Thread class directly to create and run a new thread. Even though creating threads in this fashion is easy there is still easier way to do that. ThreadPool class allows you to simply place a function in a queue which is executed by the ThreadPool. ThreadPool internally maintains a pool of threads that are used to execute your code as and when required. In fact ThreadPool operations are more efficient that using Thread class directly.

Namespaces Involved

 

Following namespaces are involved:

  • System
  • System.Threading

 

QueueUserWorkItem method

 

The QueueUserWorkItem method of ThreadPool class simply accepts an instance of type WaitCallback. The WaitCallback class in turn accepts an address of the function you want to execute. The QueueUserWorkItem method basically puts your function in queue and executes as and when a thread is available. Following example shows how this method is used:

 

Public Sub QueueUserWorkItemTest()

   Dim wc As New WaitCallback(AddressOf MyWaitCallback)

   ThreadPool.QueueUserWorkItem(wc)

End Sub

 

Public Sub MyWaitCallback(ByVal state As Object)

   Console.WriteLine(“MyWaitCallback called”)

End Sub

Here,

  1. We first created an instance of WaitCallBack delegate passing it the address of our function.
  2. We then call shared method – QueueUserWorkItem – of ThreadPool class that accepts this delegate as a parameter.
  3. The function that will be run over the thread simply outputs some text on the console.

 

RegisterWaitForSingleObject method

 

The RegisterWaitForSingleObject method of ThreadPool class accepts an instance WaitHandle class and WaitOrTimerCallback class. WaitHandle class is typically an instance of AutoResetEvent or ManualResetEvent. These classes basically signal to the ThreadPool that your function can now be called. WaitOrTimerCallback instance is nothing but a delegate for your function. Following code shows how this method is used:

 

Public Sub ShowDemoRegisterWaitForSingleObject()

   Dim wtc As New

   WaitOrTimerCallback(AddressOf MyWaitOrTimerCallback)

   Dim myevent As New AutoResetEvent(False)

   ThreadPool.RegisterWaitForSingleObject

   (myevent, wtc, Nothing, 20000, True)

   myevent.Set()

End Sub

 

Public Sub MyWaitOrTimerCallback

(ByVal state As Object, ByVal timeout As Boolean)

   Console.WriteLine(“MyWaitOrTimerCallback called”)

End Sub

Here,

  • We first create a WaitOtTimerCallBack delegate by passing it the address of our function.
  • Next, we create an instance of AutoResetEvent.
  • RegisterWaitForSingleObject method of ThreadPool class is then called.
  • Note that unless you call Set() method on the AutoResetEvent, your function will not be executed. Calling this method indicates to ThreadPool that the method can now be called on a thread from the pool.
  •  

I hope you must have found the article useful. In the next article, I will show you how to use System.Threading.Timer class to execute your function repeatedly after certain time interval.

 

 

Using Timer Class

 

Introduction

 

If you have programmed in VB6 before then probably you are familiar with Timer control. The Timer control triggers a code after certain interval of time. This control is typically used on windows forms. Similar control does exists for Windows Forms as well. What if you need such timer functionality on a thread of your classes (not on forms)? The System.Threading.Timer class can be used in such cases. This class automatically uses Thread Pool for executing your code.

Namespaces Involved

 

Following namespaces are involved:

  • System
  • System.Threading

 

Using System.Threading.Timer Class

 

In order to use Timer class you need to create an instance of it as shown below:

 

Public Sub StartTimer()

  Dim tcb As New TimerCallback(AddressOf Me.TimerMethod)

  Dim objTimer As Timer

  objTimer = New Timer(tcb, Nothing,

  TimeSpan.FromSeconds(5),

  TimeSpan.FromSeconds(10))

End Sub

 

Public Sub TimerMethod(ByVal state As Object)

   MsgBox(“The Timer invoked this method.”)

End Sub

 

Here, we created an instance of Timer class and passed a TimerCallBack and interval details to it. The third parameter represents the delay in milliseconds after which the method will be called for the first time. The forth parameter represents the interval in milliseconds that will be elapsed between the consecutive method calls. In our example the timer will start 5 seconds after creation of the instance. Then after 10 seconds it will fire again and again.

 

Advertisements

July 11, 2008 - Posted by | Delegates | ,

1 Comment »

  1. Thanks !

    Comment by ensuggemy | August 3, 2008 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: