15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

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

264 ❘ ChaPTer 10 cOllectiOns<br />

}<br />

ev.Set();<br />

});<br />

producer.Start(<br />

Tuple.Create < BlockingCollection < int > , ManualResetEventSlim > (<br />

sharedCollection, events[0]));<br />

var consumer = new Thread(obj = ><br />

{<br />

var state =<br />

(Tuple < BlockingCollection < int > , ManualResetEventSlim > )obj;<br />

var coll = state.Item1;<br />

var ev = state.Item2;<br />

for (int i = 0; i < 300; i++)<br />

{<br />

int result = coll.Take();<br />

}<br />

ev.Set();<br />

});<br />

consumer.Start(<br />

Tuple.Create < BlockingCollection < int > , ManualResetEventSlim > (<br />

sharedCollection, events[1]));<br />

if (!WaitH<strong>and</strong>le.WaitAll(waits))<br />

Console.WriteLine("wait failed");<br />

else<br />

Console.WriteLine("reading/writing finished");<br />

code snippet ConcurrentSample/Program.cs<br />

Using the concurrent collections really gets interesting as soon as multiple threads come<br />

into play. This as well as the use of the CancellationToken is shown in Chapter 20.<br />

The next chapter also gives information about using the concurrent collections with<br />

Parallel LINQ.<br />

PerformanCe<br />

Many collection classes offer the same functionality as others; for example, SortedList offers nearly the<br />

same features as SortedDictionary . However, often there ’ s a big difference in performance. Whereas one<br />

collection consumes less memory, the other collection class is faster with retrieval of elements. In the MSDN<br />

documentation, you often fi nd performance hints with methods of the collection giving you information<br />

about the time the operation represents in big - O notation:<br />

O(1)<br />

O(log n)<br />

O(n)<br />

O(1) means that the time this operation needs is constant no matter how many items are in the collection.<br />

For example, the ArrayList has an Add() method with O(1) behavior. No matter how many elements are<br />

in the list, it always takes the same time when adding a new element to the end of the list. The Count property<br />

gives the number of items, so it is easy to fi nd the end of the list.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!