19.4. Using Message Queues on a Local Workstation
Problem
You need a way to disconnect two components of your application (such as a web service endpoint and processing logic) so that the first component has to worry about only formatting the instructions, and the bulk of the processing occurs in the second component.
Solution
Use the MQWorker
class shown here in both the first and second components to write and read messages to and from a message queue. MQWorker
uses the local message-queuing services to do this. The queue pathname is supplied in the constructor, and the existence of the queue is checked in the SetUpQueue
method:
class MQWorker : IDisposable { private bool _disposed; private string _mqPathName; MessageQueue _queue; public MQWorker(string queuePathName) { if (string.IsNullOrEmpty(queuePathName) throw new ArgumentNullException("queuePathName"); _mqPathName = queuePathName; SetUpQueue(); }
SetUpQueue
creates a message queue of the supplied name using the MessageQueue
class if none exists. It accounts for the scenario in which the message-queuing services are running on a workstation computer. In that situation, it makes the queue private, as that is the only type of queue allowed on a workstation:
private void SetUpQueue() { // See if the queue exists; create it if not. if (!MessageQueue.Exists(_mqPathName)) { try { _queue = MessageQueue.Create(_mqPathName); } catch (MessageQueueException mqex) { // See if we are running on a workgroup computer. if (mqex.MessageQueueErrorCode ...
Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.