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.

238 ❘ ChaPTer 10 cOllectiOns<br />

The DocumentManager class is a thin layer around the Queue < T > class. The class DocumentManager defi nes<br />

how to h<strong>and</strong>le documents: adding documents to the queue with the AddDocument() method, <strong>and</strong> getting<br />

documents from the queue with the GetDocument() method.<br />

Inside the AddDocument() method, the document is added to the end of the queue by using the Enqueue()<br />

method. The fi rst document from the queue is read with the Dequeue() method inside GetDocument() .<br />

Because multiple threads can access the DocumentManager concurrently, access to the queue is locked with<br />

the lock statement.<br />

Threading <strong>and</strong> the lock statement are discussed in Chapter 20, “ Threads, Tasks, <strong>and</strong><br />

Synchronization.”<br />

IsDocumentAvailable is a read - only Boolean property that returns true if there are documents in the<br />

queue, <strong>and</strong> false if not:<br />

public class DocumentManager<br />

{<br />

private readonly Queue < Document > documentQueue = new Queue < Document > ();<br />

public void AddDocument(Document doc)<br />

{<br />

lock (this)<br />

{<br />

documentQueue.Enqueue(doc);<br />

}<br />

}<br />

public Document GetDocument()<br />

{<br />

Document doc = null;<br />

lock (this)<br />

{<br />

doc = documentQueue.Dequeue();<br />

}<br />

return doc;<br />

}<br />

}<br />

public bool IsDocumentAvailable<br />

{<br />

get<br />

{<br />

return documentQueue.Count > 0;<br />

}<br />

}<br />

code snippet QueueSample/DocumentManager.cs<br />

The class ProcessDocuments processes documents from the queue in a separate thread. The only<br />

method that can be accessed from the outside is Start() . In the Start() method, a new thread is<br />

instantiated. A ProcessDocuments object is created for starting the thread, <strong>and</strong> the Run() method<br />

is defi ned as the start method of the thread. ThreadStart is a delegate that references the method to<br />

be started by the thread. After creating the Thread object, the thread is started by calling the method<br />

Thread.Start() .<br />

With the Run() method of the ProcessDocuments class, an endless loop is defi ned. Within this loop, the<br />

property IsDocumentAvailable is used to see if there is a document in the queue. If there is a document in the<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!