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.

1374 ❘ ChaPTer 46 messAGe QueuinG<br />

using System.Windows.Threading;<br />

namespace Wrox.ProCSharp.Messaging<br />

{<br />

public partial class CourseOrderReceiverWindow: Window<br />

{<br />

private MessageQueue orderQueue;<br />

public CourseOrderReceiverWindow()<br />

{<br />

InitializeComponent();<br />

string queueName = CourseOrder.CourseOrderQueueName;<br />

orderQueue = new MessageQueue(queueName);<br />

orderQueue.Formatter = new XmlMessageFormatter(<br />

new Type[]<br />

{<br />

typeof(CourseOrder),<br />

typeof(Customer),<br />

typeof(Course)<br />

});<br />

}<br />

// start the task that fills the ListBox with orders<br />

Task t1 = new Task(PeekMessages);<br />

t1.Start();<br />

code snippet CourseOrderReceiver/CourseOrderReceiverWindow.xaml.cs<br />

The task’s main method, PeekMessages(), uses the enumerator of the message queue to display all<br />

messages. Within the while loop, the messagesEnumerator checks to see if there is a new message in the<br />

queue. If there is no message in the queue, the thread waits three hours for the next message to arrive<br />

before it exits.<br />

To display every message from the queue in the list box, the thread cannot directly write the text to the<br />

list box, but needs to forward the call to the list box’s creator thread. Because WPF controls are bound to a<br />

single thread, only the creator thread is allowed to access methods <strong>and</strong> properties. The Dispatcher<br />

.Invoke() method forwards the request to the creator thread:<br />

private void PeekMessages()<br />

{<br />

using (MessageEnumerator messagesEnumerator =<br />

orderQueue.GetMessageEnumerator2())<br />

{<br />

while (messagesEnumerator.MoveNext(TimeSpan.FromHours(3)))<br />

{<br />

var labelId = new LabelIdMapping()<br />

{<br />

Id = messagesEnumerator.Current.Id,<br />

Label = messagesEnumerator.Current.Label<br />

};<br />

Dispatcher.Invoke(DispatcherPriority.Normal,<br />

new Action(AddListItem),<br />

labelId);<br />

}<br />

}<br />

MessageBox.Show("No orders in the last 3 hours. Exiting thread",<br />

"Course Order Receiver", MessageBoxButton.OK,<br />

MessageBoxImage.Information);<br />

}<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!