03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

Create successful ePaper yourself

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

502 ❘ CHAPTER 22 Parallel Programming<br />

{<br />

try<br />

{<br />

// Critical code goes here ...<br />

}<br />

finally<br />

{<br />

Monitor.Exit(UpdateLock);<br />

}<br />

}<br />

else<br />

{<br />

// Do something if we time out.<br />

}<br />

The code creates the lock object UpdateLock as before. Later it uses Monitor.TryEnter to try to<br />

enter the critical region of code. If TryEnter succeeds, the thread enters its critical region and does<br />

whatever it needs to do with the resources. The finally section of the try finally block ensures<br />

that the code calls Monitor.Exit when it is done with the critical region.<br />

If the call to TryEnter returns false, the thread timed out and failed to obtain the lock. In that<br />

case the code should do something to recover, possibly trying again to obtain the lock.<br />

Limited Do-Overs<br />

If your code fails to obtain a lock, you may want to limit the number of times it can<br />

try again. If a thread becomes permanently stuck inside the critical region, it will<br />

block any other thread that must access that region.<br />

Of course, if the program is in that situation, it may be impossible to get anything<br />

done, and you may want close it and start over.<br />

The following table lists the most useful Monitor class methods.<br />

Method<br />

Enter<br />

Exit<br />

IsEntered<br />

TryEnter<br />

Wait<br />

Purpose<br />

Acquires an exclusive lock on an object.<br />

Releases an exclusive lock on an object.<br />

Returns true if the current thread has a lock on a specific object.<br />

Tries to acquire an exclusive lock on an object.<br />

Releases the lock on an object and then blocks until it reacquires a<br />

lock on that object. This is useful if the thread needs to allow another<br />

thread to take some action before it can continue.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!