MessageQueue Class (System.Messaging)

Switch View :
ScriptFree
.NET Framework Class Library
MessageQueue Class

Provides access to a queue on a Message Queuing server.

Inheritance Hierarchy

System.Object
  System.MarshalByRefObject
    System.ComponentModel.Component
      System.Messaging.MessageQueue

Namespace:  System.Messaging
Assembly:  System.Messaging (in System.Messaging.dll)
Syntax

Visual Basic
<MessagingDescriptionAttribute("MessageQueueDesc")> _
Public Class MessageQueue _
	Inherits Component _
	Implements IEnumerable
C#
[MessagingDescriptionAttribute("MessageQueueDesc")]
public class MessageQueue : Component, 
	IEnumerable
Visual C++
[MessagingDescriptionAttribute(L"MessageQueueDesc")]
public ref class MessageQueue : public Component, 
	IEnumerable
F#
[<MessagingDescriptionAttribute("MessageQueueDesc")>]
type MessageQueue =  
    class
        inherit Component
        interface IEnumerable
    end

The MessageQueue type exposes the following members.

Constructors

  Name Description
Public method MessageQueue() Initializes a new instance of the MessageQueue class. After the default constructor initializes the new instance, you must set the instance's Path property before you can use the instance.
Public method MessageQueue(String) Initializes a new instance of the MessageQueue class that references the Message Queuing queue at the specified path.
Public method MessageQueue(String, Boolean) Initializes a new instance of the MessageQueue class that references the Message Queuing queue at the specified path and with the specified read-access restriction.
Public method MessageQueue(String, QueueAccessMode) Initializes a new instance of the MessageQueue class.
Public method MessageQueue(String, Boolean, Boolean) Initializes a new instance of the MessageQueue class.
Public method MessageQueue(String, Boolean, Boolean, QueueAccessMode) Initializes a new instance of the MessageQueue class.
Top
Properties

  Name Description
Public property AccessMode Gets a value that indicates the access mode for the queue.
Public property Authenticate Gets or sets a value that indicates whether the queue accepts only authenticated messages.
Public property BasePriority Gets or sets the base priority Message Queuing uses to route a public queue's messages over the network.
Protected property CanRaiseEvents Gets a value indicating whether the component can raise an event. (Inherited from Component.)
Public property CanRead Gets a value that indicates whether the MessageQueue can be read.
Public property CanWrite Gets a value that indicates whether the MessageQueue can be written to.
Public property Category Gets or sets the queue category.
Public property Container Gets the IContainer that contains the Component. (Inherited from Component.)
Public property CreateTime Gets the time and date that the queue was created in Message Queuing.
Public property DefaultPropertiesToSend Gets or sets the message property values to be used by default when the application sends messages to the queue.
Public property DenySharedReceive Gets or sets a value that indicates whether this MessageQueue has exclusive access to receive messages from the Message Queuing queue.
Protected property DesignMode Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Public property Static member EnableConnectionCache Gets or sets a value that indicates whether a cache of connections will be maintained by the application.
Public property EncryptionRequired Gets or sets a value that indicates whether the queue accepts only non-private (non-encrypted) messages.
Protected property Events Gets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public property FormatName Gets the unique queue name that Message Queuing generated at the time of the queue's creation.
Public property Formatter Gets or sets the formatter used to serialize an object into or deserialize an object from the body of a message read from or written to the queue.
Public property Id Gets the unique Message Queuing identifier of the queue.
Public property Label Gets or sets the queue description.
Public property LastModifyTime Gets the last time the properties of a queue were modified.
Public property MachineName Gets or sets the name of the computer where the Message Queuing queue is located.
Public property MaximumJournalSize Gets or sets the maximum size of the journal queue.
Public property MaximumQueueSize Gets or sets the maximum size of the queue.
Public property MessageReadPropertyFilter Gets or sets the property filter for receiving or peeking messages.
Public property MulticastAddress Introduced in MSMQ 3.0. Gets or sets the multicast address associated with the queue.
Public property Path Gets or sets the queue's path. Setting the Path causes the MessageQueue to point to a new queue.
Public property QueueName Gets or sets the friendly name that identifies the queue.
Public property ReadHandle Gets the native handle used to read messages from the message queue.
Public property Site Gets or sets the ISite of the Component. (Inherited from Component.)
Public property SynchronizingObject Gets or sets the object that marshals the event-handler call resulting from a ReceiveCompleted or PeekCompleted event.
Public property Transactional Gets a value that indicates whether the queue accepts only transactions.
Public property UseJournalQueue Gets or sets a value that indicates whether received messages are copied to the journal queue.
Public property WriteHandle Gets the native handle used to send messages to the message queue.
Top
Methods

  Name Description
Public method BeginPeek() Initiates an asynchronous peek operation that has no time-out. The operation is not complete until a message becomes available in the queue.
Public method BeginPeek(TimeSpan) Initiates an asynchronous peek operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginPeek(TimeSpan, Object) Initiates an asynchronous peek operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginPeek(TimeSpan, Object, AsyncCallback) Initiates an asynchronous peek operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginPeek(TimeSpan, Cursor, PeekAction, Object, AsyncCallback) Initiates an asynchronous peek operation that has a specified time-out and that uses a specified cursor, a specified peek action, and a specified state object. The state object provides associated information throughout the lifetime of the operation. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginReceive() Initiates an asynchronous receive operation that has no time-out. The operation is not complete until a message becomes available in the queue.
Public method BeginReceive(TimeSpan) Initiates an asynchronous receive operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginReceive(TimeSpan, Object) Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginReceive(TimeSpan, Object, AsyncCallback) Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method BeginReceive(TimeSpan, Cursor, Object, AsyncCallback) Initiates an asynchronous receive operation that has a specified time-out and uses a specified cursor and a specified state object. The state object provides associated information throughout the lifetime of the operation. This overload receives notification, through a callback, of the identity of the event handler for the operation. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
Public method Static member ClearConnectionCache Clears the connection cache.
Public method Close Frees all resources allocated by the MessageQueue.
Public method Static member Create(String) Creates a non-transactional Message Queuing queue at the specified path.
Public method Static member Create(String, Boolean) Creates a transactional or non-transactional Message Queuing queue at the specified path.
Public method CreateCursor Creates a new Cursor for the current message queue.
Public method CreateObjRef Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Static member Delete Deletes a queue on a Message Queuing server.
Public method Dispose() Releases all resources used by the Component. (Inherited from Component.)
Protected method Dispose(Boolean) Disposes of the resources (other than memory) used by the MessageQueue. (Overrides Component.Dispose(Boolean).)
Public method EndPeek Completes the specified asynchronous peek operation.
Public method EndReceive Completes the specified asynchronous receive operation.
Public method Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Public method Static member Exists Determines whether a Message Queuing queue exists at the specified path.
Protected method Finalize Releases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public method GetAllMessages Returns all the messages that are in the queue.
Public method GetEnumerator Obsolete. Enumerates the messages in a queue. GetEnumerator is deprecated. GetMessageEnumerator2 should be used instead.
Public method GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeService Retrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Static member GetMachineId Gets the identifier of the computer on which the queue referenced by this MessageQueue is located.
Public method GetMessageEnumerator Obsolete. Creates an enumerator object for all the messages in the queue. GetMessageEnumerator is deprecated. GetMessageEnumerator2 should be used instead.
Public method GetMessageEnumerator2 Creates an enumerator object for all the messages in the queue.
Public method Static member GetMessageQueueEnumerator() Provides forward-only cursor semantics to enumerate through all public queues on the network.
Public method Static member GetMessageQueueEnumerator(MessageQueueCriteria) Provides forward-only cursor semantics to enumerate through all public queues on the network that meet the specified criteria.
Public method Static member GetPrivateQueuesByMachine Retrieves all the private queues on the specified computer.
Public method Static member GetPublicQueues() Retrieves all the public queues on the network.
Public method Static member GetPublicQueues(MessageQueueCriteria) Retrieves all the public queues on the network that meet the specified criteria.
Public method Static member GetPublicQueuesByCategory Retrieves all the public queues on the network that belong to the specified category.
Public method Static member GetPublicQueuesByLabel Retrieves all the public queues on the network that carry the specified label.
Public method Static member GetPublicQueuesByMachine Retrieves all the public queues that reside on the specified computer.
Public method Static member GetSecurityContext Retrieves the security context that MSMQ associates with the current user (thread identity) at the time of this call.
Protected method GetService Returns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public method GetType Gets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeService Obtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean) Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method Peek() Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek method is synchronous, so it blocks the current thread until a message becomes available.
Public method Peek(TimeSpan) Returns without removing (peeks) the first message in the queue referenced by this MessageQueue. The Peek method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.
Public method Peek(TimeSpan, Cursor, PeekAction) Returns without removing (peeks) the current or next message in the queue, using the specified cursor. The Peek method is synchronous, so it blocks the current thread until a message becomes available or the specified time-out occurs.
Public method PeekByCorrelationId(String) Peeks the message that matches the given correlation identifier and immediately raises an exception if no message with the specified correlation identifier currently exists in the queue.
Public method PeekByCorrelationId(String, TimeSpan) Peeks the message that matches the given correlation identifier and waits until either a message with the specified correlation identifier is available in the queue, or the time-out expires.
Public method PeekById(String) Peeks the message whose message identifier matches the id parameter.
Public method PeekById(String, TimeSpan) Peeks the message whose message identifier matches the id parameter. Waits until the message appears in the queue or a time-out occurs.
Public method PeekByLookupId(Int64) Introduced in MSMQ 3.0. Peeks at the message that matches the given lookup identifier from a non-transactional queue.
Public method PeekByLookupId(MessageLookupAction, Int64) Introduced in MSMQ 3.0. Peeks at a specific message from the queue. The message can be specified by a lookup identifier or by its position at the front or end of the queue.
Public method Purge Deletes all the messages contained in the queue.
Public method Receive() Receives the first message available in the queue referenced by the MessageQueue. This call is synchronous, and blocks the current thread of execution until a message is available.
Public method Receive(MessageQueueTransaction) Receives the first message available in the transactional queue referenced by the MessageQueue. This call is synchronous, and blocks the current thread of execution until a message is available.
Public method Receive(MessageQueueTransactionType) Receives the first message available in the queue referenced by the MessageQueue. This call is synchronous, and blocks the current thread of execution until a message is available.
Public method Receive(TimeSpan) Receives the first message available in the queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.
Public method Receive(TimeSpan, Cursor) Receives the current message in the queue, using a specified cursor. If no message is available, this method waits until either a message is available, or the time-out expires.
Public method Receive(TimeSpan, MessageQueueTransaction) Receives the first message available in the transactional queue referenced by the MessageQueue and waits until either a message is available in the queue, or the time-out expires.
Public method Receive(TimeSpan, MessageQueueTransactionType) Receives the first message available in the queue referenced by the MessageQueue. This call is synchronous, and waits until either a message is available in the queue, or the time-out expires.
Public method Receive(TimeSpan, Cursor, MessageQueueTransaction) Receives the current message in the queue, using a specified cursor. If no message is available, this method waits until either a message is available, or the time-out expires.
Public method Receive(TimeSpan, Cursor, MessageQueueTransactionType) Receives the current message in the queue, using a specified cursor. If no message is available, this method waits until either a message is available, or the time-out expires.
Public method ReceiveByCorrelationId(String) Receives the message that matches the given correlation identifier (from a non-transactional queue) and immediately raises an exception if no message with the specified correlation identifier currently exists in the queue.
Public method ReceiveByCorrelationId(String, MessageQueueTransaction) Receives the message that matches the given correlation identifier (from a transactional queue) and immediately raises an exception if no message with the specified correlation identifier currently exists in the queue.
Public method ReceiveByCorrelationId(String, MessageQueueTransactionType) Receives the message that matches the given correlation identifier and immediately raises an exception if no message with the specified correlation identifier currently exists in the queue.
Public method ReceiveByCorrelationId(String, TimeSpan) Receives the message that matches the given correlation identifier (from a non-transactional queue) and waits until either a message with the specified correlation identifier is available in the queue, or the time-out expires.
Public method ReceiveByCorrelationId(String, TimeSpan, MessageQueueTransaction) Receives the message that matches the given correlation identifier (from a transactional queue) and waits until either a message with the specified correlation identifier is available in the queue, or the time-out expires.
Public method ReceiveByCorrelationId(String, TimeSpan, MessageQueueTransactionType) Receives the message that matches the given correlation identifier and waits until either a message with the specified correlation identifier is available in the queue, or the time-out expires.
Public method ReceiveById(String) Receives the message that matches the given identifier from a non-transactional queue and immediately raises an exception if no message with the specified identifier currently exists in the queue.
Public method ReceiveById(String, MessageQueueTransaction) Receives the message that matches the given identifier (from a transactional queue) and immediately raises an exception if no message with the specified identifier currently exists in the queue.
Public method ReceiveById(String, MessageQueueTransactionType) Receives the message that matches the given identifier and immediately raises an exception if no message with the specified identifier currently exists in the queue.
Public method ReceiveById(String, TimeSpan) Receives the message that matches the given identifier (from a non-transactional queue) and waits until either a message with the specified identifier is available in the queue or the time-out expires.
Public method ReceiveById(String, TimeSpan, MessageQueueTransaction) Receives the message that matches the given identifier (from a transactional queue) and waits until either a message with the specified identifier is available in the queue or the time-out expires.
Public method ReceiveById(String, TimeSpan, MessageQueueTransactionType) Receives the message that matches the given identifier and waits until either a message with the specified identifier is available in the queue or the time-out expires.
Public method ReceiveByLookupId(Int64) Introduced in MSMQ 3.0. Receives the message that matches the given lookup identifier from a non-transactional queue.
Public method ReceiveByLookupId(MessageLookupAction, Int64, MessageQueueTransaction) Introduced in MSMQ 3.0. Receives a specific message from a transactional queue. The message can be specified by a lookup identifier or by its position at the front or end of the queue.
Public method ReceiveByLookupId(MessageLookupAction, Int64, MessageQueueTransactionType) Introduced in MSMQ 3.0. Receives a specific message from the queue, using the specified transaction context. The message can be specified by a lookup identifier or by its position at the front or end of the queue.
Public method Refresh Refreshes the properties presented by the MessageQueue to reflect the current state of the resource.
Public method ResetPermissions Resets the permission list to the operating system's default values. Removes any queue permissions you have appended to the default list.
Public method Send(Object) Sends an object to non-transactional queue referenced by this MessageQueue.
Public method Send(Object, MessageQueueTransaction) Sends an object to the transactional queue referenced by this MessageQueue.
Public method Send(Object, MessageQueueTransactionType) Sends an object to the queue referenced by this MessageQueue.
Public method Send(Object, String) Sends an object to the non-transactional queue referenced by this MessageQueue and specifies a label for the message.
Public method Send(Object, String, MessageQueueTransaction) Sends an object to the transactional queue referenced by this MessageQueue and specifies a label for the message.
Public method Send(Object, String, MessageQueueTransactionType) Sends an object to the queue referenced by this MessageQueue and specifies a label for the message.
Public method SetPermissions(AccessControlList) Assigns access rights to the queue based on the contents of an access control list.
Public method SetPermissions(MessageQueueAccessControlEntry) Assigns access rights to the queue based on the contents of an access control entry.
Public method SetPermissions(String, MessageQueueAccessRights) Gives a computer, group, or user the specified access rights.
Public method SetPermissions(String, MessageQueueAccessRights, AccessControlEntryType) Gives a computer, group, or user the specified access rights, with the specified access control type (allow, deny, revoke, or set).
Public method ToString Returns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Top
Events

  Name Description
Public event Disposed Occurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public event PeekCompleted Occurs when a message is read without being removed from the queue. This is a result of the asynchronous operation, BeginPeek.
Public event ReceiveCompleted Occurs when a message has been removed from the queue. This event is raised by the asynchronous operation, BeginReceive.
Top
Extension Methods

  Name Description
Public Extension Method AsParallel Enables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension Method AsQueryable Converts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension Method Cast<TResult> Converts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension Method OfType<TResult> Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Top
Fields

  Name Description
Public field Static member InfiniteQueueSize Specifies that no size restriction exists for a queue.
Public field Static member InfiniteTimeout Specifies that no time-out exists for methods that peek or receive messages.
Top
Remarks

The Message Queuing technology allows applications running at different times to communicate across heterogeneous networks and systems that might be temporarily offline. Applications send, receive, or peek (read without removing) messages from queues. Message Queuing is an optional component of Windows 2000 and Windows NT, and must be installed separately.

The MessageQueue class is a wrapper around Message Queuing. There are multiple versions of Message Queuing, and using the MessageQueue class can result in slightly different behavior, depending on the operating system you are using. For information about specific features of each version of Message Queuing, see the topic "What's New in Message Queuing" in the Platform SDK in MSDN.

The MessageQueue class provides a reference to a Message Queuing queue. You can specify a path in the MessageQueue constructor to connect to an existing resource, or you can create a new queue on the server. Before you can call Send(Object), Peek, or Receive, you must associate the new instance of the MessageQueue class with an existing queue. At that point, you can manipulate the queue properties such as Category and Label.

MessageQueue supports two types of message retrieval: synchronous and asynchronous. The synchronous methods, Peek and Receive, cause the process thread to wait a specified time interval for a new message to arrive in the queue. The asynchronous methods, BeginPeek and BeginReceive, allow the main application tasks to continue in a separate thread until a message arrives in the queue. These methods work by using callback objects and state objects to communicate information between threads.

When you create a new instance of the MessageQueue class, you are not creating a new Message Queuing queue. Instead, you can use the Create(String), Delete(String), and Purge methods to manage queues on the server.

Unlike Purge, Create(String) and Delete(String) are static members, so you can call them without creating a new instance of the MessageQueue class.

You can set the MessageQueue object's Path property with one of three names: the friendly name, the FormatName, or the Label. The friendly name, which is defined by the queue's MachineName and QueueName properties, is MachineName\QueueName for a public queue, and MachineName\Private$\QueueName for a private queue. The FormatName property allows offline access to message queues. Lastly, you can use the queue's Label property to set the queue's Path.

For a list of initial property values for an instance of MessageQueue, see the MessageQueue constructor.

Examples

The following code example creates new MessageQueue objects using various path name syntax types. In each case, it sends a message to the queue whose path is defined in the constructor.

Visual Basic

Imports System
Imports System.Messaging

Public Class MyNewQueue



        ' Provides an entry point into the application.
        '		 
        ' This example demonstrates several ways to set
        ' a queue's path.


        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue()

            myNewQueue.SendPublic()
            myNewQueue.SendPrivate()
            myNewQueue.SendByLabel()
            myNewQueue.SendByFormatName()
            myNewQueue.MonitorComputerJournal()
            myNewQueue.MonitorQueueJournal()
            myNewQueue.MonitorDeadLetter()
            myNewQueue.MonitorTransactionalDeadLetter()

            Return

        End Sub 'Main


        ' References public queues.
        Public Sub SendPublic()

            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Send("Public queue by path name.")

            Return

        End Sub 'SendPublic


        ' References private queues.
        Public Sub SendPrivate()

            Dim myQueue As New MessageQueue(".\Private$\myQueue")
            myQueue.Send("Private queue by path name.")

            Return

        End Sub 'SendPrivate


        ' References queues by label.
        Public Sub SendByLabel()

            Dim myQueue As New MessageQueue("Label:TheLabel")
            myQueue.Send("Queue by label.")

            Return

        End Sub 'SendByLabel


        ' References queues by format name.
        Public Sub SendByFormatName()

            Dim myQueue As New _
                MessageQueue("FormatName:Public=" + _
                    "5A5F7535-AE9A-41d4-935C-845C2AFF7112")
            myQueue.Send("Queue by format name.")

            Return

        End Sub 'SendByFormatName


        ' References computer journal queues.
        Public Sub MonitorComputerJournal()

            Dim computerJournal As New MessageQueue(".\Journal$")

            While True

                Dim journalMessage As Message = _
                    computerJournal.Receive()

                ' Process the journal message.

            End While

            Return
        End Sub 'MonitorComputerJournal


        ' References queue journal queues.
        Public Sub MonitorQueueJournal()

            Dim queueJournal As New _
                            MessageQueue(".\myQueue\Journal$")

            While True

                Dim journalMessage As Message = _
                    queueJournal.Receive()

                ' Process the journal message.

            End While

            Return
        End Sub 'MonitorQueueJournal


        ' References dead-letter queues.
        Public Sub MonitorDeadLetter()
            Dim deadLetter As New MessageQueue(".\DeadLetter$")

            While True

                Dim deadMessage As Message = deadLetter.Receive()

                ' Process the dead-letter message.

            End While

            Return

        End Sub 'MonitorDeadLetter


        ' References transactional dead-letter queues.
        Public Sub MonitorTransactionalDeadLetter()

            Dim TxDeadLetter As New MessageQueue(".\XactDeadLetter$")

            While True

                Dim txDeadLetterMessage As Message = _
                    TxDeadLetter.Receive()

                ' Process the transactional dead-letter message.

            End While

            Return

        End Sub 'MonitorTransactionalDeadLetter

End Class 'MyNewQueue 



C#

using System;
using System.Messaging;

namespace MyProject
{
	/// <summary>
	/// Provides a container class for the example.
	/// </summary>
	public class MyNewQueue
	{

		//**************************************************
		// Provides an entry point into the application.
		//		 
		// This example demonstrates several ways to set
		// a queue's path.
		//**************************************************

		public static void Main()
		{
			// Create a new instance of the class.
			MyNewQueue myNewQueue = new MyNewQueue();

			myNewQueue.SendPublic();
			myNewQueue.SendPrivate();
			myNewQueue.SendByLabel();
			myNewQueue.SendByFormatName();
			myNewQueue.MonitorComputerJournal();
			myNewQueue.MonitorQueueJournal();
			myNewQueue.MonitorDeadLetter();
			myNewQueue.MonitorTransactionalDeadLetter();

			return;
		}
		
		// References public queues.
		public void SendPublic()
		{
			MessageQueue myQueue = new MessageQueue(".\\myQueue");
			myQueue.Send("Public queue by path name.");

			return;
		}

		// References private queues.
		public void SendPrivate()
		{
			MessageQueue myQueue = new 
				MessageQueue(".\\Private$\\myQueue");
			myQueue.Send("Private queue by path name.");

			return;
		}

		// References queues by label.
		public void SendByLabel()
		{
			MessageQueue myQueue = new MessageQueue("Label:TheLabel");
			myQueue.Send("Queue by label.");

			return;
		}

		// References queues by format name.
		public void SendByFormatName()
		{
			MessageQueue myQueue = new 
				MessageQueue("FormatName:Public=5A5F7535-AE9A-41d4" + 
				"-935C-845C2AFF7112");
			myQueue.Send("Queue by format name.");

			return;
		}

		// References computer journal queues.
		public void MonitorComputerJournal()
		{
			MessageQueue computerJournal = new 
				MessageQueue(".\\Journal$");
			while(true)
			{
				Message journalMessage = computerJournal.Receive();
				// Process the journal message.
			}
		}

		// References queue journal queues.
		public void MonitorQueueJournal()
		{
			MessageQueue queueJournal = new 
				MessageQueue(".\\myQueue\\Journal$");
			while(true)
			{
				Message journalMessage = queueJournal.Receive();
				// Process the journal message.
			}
		}
		
		// References dead-letter queues.
		public void MonitorDeadLetter()
		{
			MessageQueue deadLetter = new 
				MessageQueue(".\\DeadLetter$");
			while(true)
			{
				Message deadMessage = deadLetter.Receive();
				// Process the dead-letter message.
			}
		}

		// References transactional dead-letter queues.
		public void MonitorTransactionalDeadLetter()
		{
			MessageQueue TxDeadLetter = new 
				MessageQueue(".\\XactDeadLetter$");
			while(true)
			{
				Message txDeadLetter = TxDeadLetter.Receive();
				// Process the transactional dead-letter message.
			}
		}

	}
}


Visual C++

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;
ref class MyNewQueue
{
public:

   // References public queues.
   void SendPublic()
   {
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
      myQueue->Send( "Public queue by path name." );
      return;
   }


   // References private queues.
   void SendPrivate()
   {
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\Private$\\myQueue" );
      myQueue->Send( "Private queue by path name." );
      return;
   }


   // References queues by label.
   void SendByLabel()
   {
      MessageQueue^ myQueue = gcnew MessageQueue( "Label:TheLabel" );
      myQueue->Send( "Queue by label." );
      return;
   }


   // References queues by format name.
   void SendByFormatName()
   {
      MessageQueue^ myQueue = gcnew MessageQueue( "FormatName:Public=5A5F7535-AE9A-41d4 -935C-845C2AFF7112" );
      myQueue->Send( "Queue by format name." );
      return;
   }


   // References computer journal queues.
   void MonitorComputerJournal()
   {
      MessageQueue^ computerJournal = gcnew MessageQueue( ".\\Journal$" );
      while ( true )
      {
         Message^ journalMessage = computerJournal->Receive();

         // Process the journal message.
      }
   }


   // References queue journal queues.
   void MonitorQueueJournal()
   {
      MessageQueue^ queueJournal = gcnew MessageQueue( ".\\myQueue\\Journal$" );
      while ( true )
      {
         Message^ journalMessage = queueJournal->Receive();

         // Process the journal message.
      }
   }


   // References dead-letter queues.
   void MonitorDeadLetter()
   {
      MessageQueue^ deadLetter = gcnew MessageQueue( ".\\DeadLetter$" );
      while ( true )
      {
         Message^ deadMessage = deadLetter->Receive();

         // Process the dead-letter message.
      }
   }


   // References transactional dead-letter queues.
   void MonitorTransactionalDeadLetter()
   {
      MessageQueue^ TxDeadLetter = gcnew MessageQueue( ".\\XactDeadLetter$" );
      while ( true )
      {
         Message^ txDeadLetter = TxDeadLetter->Receive();

         // Process the transactional dead-letter message.
      }
   }

};


//*************************************************
// Provides an entry point into the application.
//         
// This example demonstrates several ways to set
// a queue's path.
//*************************************************
int main()
{

   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;
   myNewQueue->SendPublic();
   myNewQueue->SendPrivate();
   myNewQueue->SendByLabel();
   myNewQueue->SendByFormatName();
   myNewQueue->MonitorComputerJournal();
   myNewQueue->MonitorQueueJournal();
   myNewQueue->MonitorDeadLetter();
   myNewQueue->MonitorTransactionalDeadLetter();
   return 0;
}



The following code example sends a message to a queue, and receives a message from a queue, using an application-specific class called Order.

Visual Basic

Imports System
Imports System.Messaging

    ' This class represents an object the following example 
    ' sends to a queue and receives from a queue.
    Public Class Order
        Public orderId As Integer
        Public orderTime As DateTime
    End Class 'Order



    Public Class MyNewQueue


        '
        ' Provides an entry point into the application.
        '		 
        ' This example sends and receives a message from
        ' a qeue.
        '

        Public Shared Sub Main()

            ' Create a new instance of the class.
            Dim myNewQueue As New MyNewQueue()

            ' Send a message to a queue.
            myNewQueue.SendMessage()

            ' Receive a message from a queue.
            myNewQueue.ReceiveMessage()

            Return

        End Sub 'Main


        '
        ' Sends an Order to a queue.
        '

        Public Sub SendMessage()

            ' Create a new order and set values.
            Dim sentOrder As New Order()
            sentOrder.orderId = 3
            sentOrder.orderTime = DateTime.Now

            ' Connect to a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")

            ' Send the Order to the queue.
            myQueue.Send(sentOrder)

            Return

        End Sub 'SendMessage


        '
        ' Receives a message containing an Order.
        '

        Public Sub ReceiveMessage()

            ' Connect to the a queue on the local computer.
            Dim myQueue As New MessageQueue(".\myQueue")

            ' Set the formatter to indicate the body contains an Order.
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType(Order)})

            Try

                ' Receive and format the message. 
                Dim myMessage As Message = myQueue.Receive()
                Dim myOrder As Order = CType(myMessage.Body, Order)

                ' Display message information.
                Console.WriteLine(("Order ID: " + _
                    myOrder.orderId.ToString()))
                Console.WriteLine(("Sent: " + _
                    myOrder.orderTime.ToString()))

            Catch m As MessageQueueException
                ' Handle Message Queuing exceptions.

            Catch e As InvalidOperationException
                ' Handle invalid serialization format.
                Console.WriteLine(e.Message)


                ' Catch other exceptions as necessary.

            End Try

            Return

        End Sub 'ReceiveMessage

End Class 'MyNewQueue



C#

using System;
using System.Messaging;

namespace MyProject
{

	// This class represents an object the following example 
	// sends to a queue and receives from a queue.
	public class Order
	{
		public int orderId;
		public DateTime orderTime;
	};	

	/// <summary>
	/// Provides a container class for the example.
	/// </summary>
	public class MyNewQueue
	{

		//**************************************************
		// Provides an entry point into the application.
		//		 
		// This example sends and receives a message from
		// a queue.
		//**************************************************

		public static void Main()
		{
			// Create a new instance of the class.
			MyNewQueue myNewQueue = new MyNewQueue();

			// Send a message to a queue.
			myNewQueue.SendMessage();

			// Receive a message from a queue.
			myNewQueue.ReceiveMessage();

			return;
		}


		//**************************************************
		// Sends an Order to a queue.
		//**************************************************
		
		public void SendMessage()
		{
			
			// Create a new order and set values.
			Order sentOrder = new Order();
			sentOrder.orderId = 3;
			sentOrder.orderTime = DateTime.Now;

			// Connect to a queue on the local computer.
			MessageQueue myQueue = new MessageQueue(".\\myQueue");

			// Send the Order to the queue.
			myQueue.Send(sentOrder);

			return;
		}


		//**************************************************
		// Receives a message containing an Order.
		//**************************************************
		
		public  void ReceiveMessage()
		{
			// Connect to the a queue on the local computer.
			MessageQueue myQueue = new MessageQueue(".\\myQueue");

			// Set the formatter to indicate body contains an Order.
			myQueue.Formatter = new XmlMessageFormatter(new Type[]
				{typeof(MyProject.Order)});
			
			try
			{
				// Receive and format the message. 
				Message myMessage =	myQueue.Receive(); 
				Order myOrder = (Order)myMessage.Body;

				// Display message information.
				Console.WriteLine("Order ID: " + 
					myOrder.orderId.ToString());
				Console.WriteLine("Sent: " + 
					myOrder.orderTime.ToString());
			}
			
			catch (MessageQueueException)
			{
				// Handle Message Queuing exceptions.
			}

			// Handle invalid serialization format.
			catch (InvalidOperationException e)
			{
				Console.WriteLine(e.Message);
			}
			
			// Catch other exceptions as necessary.

			return;
		}
	}
}


Visual C++

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;

// This class represents an object the following example 
// sends to a queue and receives from a queue.
ref class Order
{
public:
   int orderId;
   DateTime orderTime;
};


/// <summary>
/// Provides a container class for the example.
/// </summary>
ref class MyNewQueue
{
public:

   //*************************************************
   // Sends an Order to a queue.
   //*************************************************
   void SendMessage()
   {
      // Create a new order and set values.
      Order^ sentOrder = gcnew Order;
      sentOrder->orderId = 3;
      sentOrder->orderTime = DateTime::Now;

      // Connect to a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Send the Order to the queue.
      myQueue->Send( sentOrder );
      return;
   }

   //*************************************************
   // Receives a message containing an Order.
   //*************************************************
   void ReceiveMessage()
   {
      // Connect to the a queue on the local computer.
      MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );

      // Set the formatter to indicate body contains an Order.
      array<Type^>^p = gcnew array<Type^>(1);
      p[ 0 ] = Order::typeid;
      myQueue->Formatter = gcnew XmlMessageFormatter( p );
      try
      {
         // Receive and format the message. 
         Message^ myMessage = myQueue->Receive();
         Order^ myOrder = static_cast<Order^>(myMessage->Body);

         // Display message information.
         Console::WriteLine( "Order ID: {0}", myOrder->orderId );
         Console::WriteLine( "Sent: {0}", myOrder->orderTime );
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle Message Queuing exceptions.
      }
      // Handle invalid serialization format.
      catch ( InvalidOperationException^ e ) 
      {
         Console::WriteLine( e->Message );
      }

      // Catch other exceptions as necessary.
      return;
   }
};

//*************************************************
// Provides an entry point into the application.
//         
// This example sends and receives a message from
// a queue.
//*************************************************
int main()
{
   // Create a new instance of the class.
   MyNewQueue^ myNewQueue = gcnew MyNewQueue;

   // Send a message to a queue.
   myNewQueue->SendMessage();

   // Receive a message from a queue.
   myNewQueue->ReceiveMessage();
   return 0;
}


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Only the GetAllMessages method is thread safe.

See Also

Reference