Synchronizing .Net Threads

The most frequently used method of synchronizing threads in a Windows application is by the use CriticalSections.  The .Net equivalent is the Monitor class.  This class controls simultaneous access to, well anything really, by ‘locking’ a class instance.  For example:

 

TMyClass = class

Private

Procedure ThreadProc;

End;

 

Procedure TMyClass.ThreadProc;

Begin

Monitor.Enter(Self);

Try

Finally

Monitor.Leave(Self);

End;

End;

 

The lock can be applied to any object, not just self.

 

There are several different classes available for thread synchronization:  Mutex, Interlocked, AutoResetEvent, ManualResetEvent, etc.

Comments are closed.