15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

synchronization ❘ 521<br />

monitor<br />

The <strong>C#</strong> compiler resolves the lock statement to use the Monitor class. The following lock statement:<br />

lock (obj)<br />

{<br />

// synchronized region for obj<br />

}<br />

is resolved to invoking the Enter() method, which waits until the thread gets the lock of the object. Only<br />

one thread at a time may be the owner of the object lock. As soon as the lock is resolved, the thread can<br />

enter the synchronized section. The Exit() method of the Monitor class releases the lock. The compiler<br />

puts the Exit() method into a finally h<strong>and</strong>ler of a try block so that the lock is also released if an<br />

exception is thrown.<br />

try / finally is covered in Chapter 15, “ Errors <strong>and</strong> Exceptions.”<br />

Monitor.Enter(obj);<br />

try<br />

{<br />

// synchronized region for obj<br />

}<br />

finally<br />

{<br />

Monitor.Exit(obj);<br />

}<br />

code snippet SynchronizationSamples/Program.cs<br />

The Monitor class has a big advantage compared to the lock statement of <strong>C#</strong>: you can add a timeout value<br />

for waiting to get the lock. So instead of endlessly waiting to get the lock, you can use the TryEnter()<br />

method, where you can pass a timeout value that defi nes the maximum amount of time to wait to get the<br />

lock. If the lock for obj is acquired, TryEnter() sets the Boolean ref parameter to true <strong>and</strong> performs<br />

synchronized access to the state guarded by the object obj . If obj is locked for more than 500 milliseconds<br />

by another thread, TryEnter() sets the variable lockTaken to false , <strong>and</strong> the thread does not wait any<br />

longer but is used to do something else. Maybe at a later time, the thread can try to acquire the lock<br />

once more.<br />

bool lockTaken = false;<br />

Monitor.TryEnter(obj, 500, ref lockTaken);<br />

if (lockTaken)<br />

{<br />

try<br />

{<br />

// acquired the lock<br />

// synchronized region for obj<br />

}<br />

finally<br />

{<br />

Monitor.Exit(obj);<br />

}<br />

}<br />

else<br />

{<br />

// didn't get the lock, do something else<br />

}<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!