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 ❘ 517<br />

}<br />

lock (this)<br />

{<br />

// only one thread at a time can access the DoThis <strong>and</strong> DoThat methods<br />

}<br />

}<br />

public void DoThat()<br />

{<br />

lock (this)<br />

{<br />

}<br />

}<br />

However, because the object of the instance can also be used for synchronized access from the outside, <strong>and</strong><br />

you can’t control this from the class itself, you can apply the SyncRoot pattern. With the SyncRoot pattern,<br />

a private object named syncRoot is created, <strong>and</strong> this object is used with the lock statements:<br />

public class Demo<br />

{<br />

private object syncRoot = new object();<br />

}<br />

public void DoThis()<br />

{<br />

lock (syncRoot)<br />

{<br />

// only one thread at a time can access the DoThis <strong>and</strong> DoThat methods<br />

}<br />

}<br />

public void DoThat()<br />

{<br />

lock (syncRoot)<br />

{<br />

}<br />

}<br />

Using locks costs time <strong>and</strong> is not always needed. You can create two versions of a class: a synchronized <strong>and</strong><br />

a nonsynchronized version. This is demonstrated here by changing the class Demo. The class Demo itself is<br />

not synchronized, as you can see in the implementation of the DoThis() <strong>and</strong> DoThat() methods. The class<br />

also defines the IsSynchronized property, where the client can get information about the synchronization<br />

option of the class. To make a synchronized variant of the class, the static method Synchronized() can<br />

be used to pass a nonsynchronized object, <strong>and</strong> this method returns an object of type SynchronizedDemo.<br />

SynchronizedDemo is implemented as an inner class that is derived from the base class Demo <strong>and</strong> overrides<br />

the virtual members of the base class. The overridden members make use of the SyncRoot pattern.<br />

public class Demo<br />

{<br />

private class SynchronizedDemo: Demo<br />

{<br />

private object syncRoot = new object();<br />

private Demo d;<br />

public SynchronizedDemo(Demo d)<br />

{<br />

this.d = d;<br />

}<br />

public override bool IsSynchronized<br />

{<br />

get { return true; }<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!