15.02.2015 Views

C# 4 and .NET 4

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

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

synchronization ❘ 531<br />

The ReaderWriterLockSlim class has properties to acquire a read lock that are blocking <strong>and</strong> nonblocking,<br />

such as EnterReadLock() <strong>and</strong> TryEnterReadLock(), <strong>and</strong> to acquire a write lock with EnterWriteLock()<br />

<strong>and</strong> TryEnterWriteLock(). If a task reads first <strong>and</strong> writes afterward, it can acquire an upgradable<br />

read lock with EnterUpgradableReadLock() or TryEnterUpgradableReadLock(). With this lock,<br />

the write lock can be acquired without releasing the read lock.<br />

Several properties of this class offer information about the held locks, for example, CurrentReadCount,<br />

WaitingReadCount, WaitingUpgradableReadCount, <strong>and</strong> WaitingWriteCount.<br />

The sample program creates a collection containing six items <strong>and</strong> a ReaderWriterLockSlim object. The<br />

method ReaderMethod() acquires a read lock to read all items of the list <strong>and</strong> write them to the console.<br />

The method WriterMethod() tries to acquire a write lock to change all values of the collection. In the<br />

Main() method, six threads are started that invoke either the method ReaderMethod() or the method<br />

WriterMethod().<br />

using System;<br />

using System.Collections.Generic;<br />

using System.Threading;<br />

using System.Threading.Tasks;<br />

namespace Wrox.ProCSharp.Threading<br />

{<br />

class Program<br />

{<br />

private static List items = new List() { 0, 1, 2, 3, 4, 5};<br />

private static ReaderWriterLockSlim rwl =<br />

new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);<br />

static void ReaderMethod(object reader)<br />

{<br />

try<br />

{<br />

rwl.EnterReadLock();<br />

}<br />

for (int i = 0; i < items.Count; i++)<br />

{<br />

Console.WriteLine("reader {0}, loop: {1}, item: {2}",<br />

reader, i, items[i]);<br />

Thread.Sleep(40);<br />

}<br />

}<br />

finally<br />

{<br />

rwl.ExitReadLock();<br />

}<br />

static void WriterMethod(object writer)<br />

{<br />

try<br />

{<br />

while (!rwl.TryEnterWriteLock(50))<br />

{<br />

Console.WriteLine("Writer {0} waiting for the write lock",<br />

writer);<br />

Console.WriteLine("current reader count: {0}",<br />

rwl.CurrentReadCount);<br />

}<br />

Console.WriteLine("Writer {0} acquired the lock", writer);<br />

for (int i = 0; i < items.Count; i++)<br />

{<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!