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.

520 ❘ ChaPTer 20 threAds, tAsks, And synchrOnizAtiOn<br />

}<br />

}<br />

lock (syncRoot)<br />

{<br />

return ++state;<br />

}<br />

code snippet SynchronizationSamples/SharedState.cs<br />

There is, however, a faster way to lock the increment of the state, as shown next.<br />

interlocked<br />

The Interlocked class is used to make simple statements for variables atomic. i++ is not thread-safe.<br />

i++ consists of getting a value from the memory, incrementing the value by 1, <strong>and</strong> storing the value back<br />

in memory. These operations can be interrupted by the thread scheduler. The Interlocked class provides<br />

methods for incrementing, decrementing, exchanging, <strong>and</strong> reading values in a thread-safe manner.<br />

Using the Interlocked class is much faster than other synchronization techniques. However, you can use it<br />

only for simple synchronization issues.<br />

For example, instead of using the lock statement to lock access to the variable someState when setting it to<br />

a new value, in case it is null, you can use the Interlocked class, which is faster:<br />

lock (this)<br />

{<br />

if (someState == null)<br />

{<br />

someState = newState;<br />

}<br />

}<br />

code snippet SynchronizationSamples/SharedState.cs<br />

The faster version with the same functionality uses the Interlocked.CompareExchange() method:<br />

Interlocked.CompareExchange(ref someState,<br />

newState, null);<br />

And instead of performing incrementing inside a lock statement:<br />

public int State<br />

{<br />

get<br />

{<br />

lock (this)<br />

{<br />

return ++state;<br />

}<br />

}<br />

}<br />

You can use Interlocked.Increment(), which is faster:<br />

public int State<br />

{<br />

get<br />

{<br />

return Interlocked.Increment(ref state);<br />

}<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!