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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 22 ❘ 709<br />

The DeadUnlock example program uses the following code for Task A.<br />

// Task A.<br />

private void TaskA()<br />

{<br />

for (int attempts = 0; attempts < 10; attempts++)<br />

{<br />

Console.WriteLine("TaskA: Locking A");<br />

if (Monitor.TryEnter(LockObjectA))<br />

{<br />

try<br />

{<br />

Thread.Sleep(1);<br />

Console.WriteLine("TaskA: Locking B");<br />

if (Monitor.TryEnter(LockObjectB))<br />

{<br />

try<br />

{<br />

// Update the value.<br />

BestValue = ValueA;<br />

}<br />

}<br />

// We're done. Break out of the retry loop.<br />

Console.WriteLine("Task A: Done");<br />

return;<br />

}<br />

finally<br />

{<br />

Console.WriteLine("Task A: Releasing lock B");<br />

Monitor.Exit(LockObjectB);<br />

}<br />

}<br />

else<br />

{<br />

Console.WriteLine("Task A: Lock B failed");<br />

}<br />

}<br />

finally<br />

{<br />

Console.WriteLine("Task A: Releasing lock A");<br />

Monitor.Exit(LockObjectA);<br />

}<br />

}<br />

else<br />

{<br />

Console.WriteLine("Task A: Lock A failed");<br />

}<br />

The code used by Task B is similar so it isn’t shown here. The only difference is that Task B<br />

tries to lock LockObjectB first and LockObjectA second.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!