Applying the lock Keyword

One of the simpler synchronization techniques to employ is the lock keyword, which offers an easy way to protect a resource. Similar to the Monitor class, the lock keyword employs the critical section technique to protect a resource. The lock keyword takes one parameter:

lock(object obj)

This parameter is an object and as such must be a reference type, not a value type. To protect a resource using the lock keyword, simply wrap the code in a lock block. The following code demonstrates how to lock a section of code:

lock(this)
{
  // Resource Protected Code
  counterVariable++;
}

Raising Thread Events

Introduced in Win32, events were used to synchronize threads by signaling other threads that it was okay to proceed with ...

Get Microsoft® Visual C#® .NET 2003 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.