Export (0) Print
Expand All

MessageQueue Class

Provides access to a queue on a Message Queuing server.

For a list of all members of this type, see MessageQueue Members.

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

[Visual Basic]
Public Class MessageQueue
   Inherits Component
   Implements IEnumerable
[C#]
public class MessageQueue : Component, IEnumerable
[C++]
public __gc class MessageQueue : public Component, IEnumerable
[JScript]
public class MessageQueue extends Component implements IEnumerable

Thread Safety

Only the following methods are safe for multithreaded operations: BeginPeek, BeginReceive, EndPeek, EndReceive, GetAllMessages, and Peek, Receive.

Remarks

Message Queuing technology allows applications running at different times to communicate across heterogeneous networks and systems, which 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, 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, Delete, and Purge methods to manage queues on the server.

Note   Unlike Purge, Create and Delete are static (Shared in Visual Basic) 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.

Example

[Visual Basic, C#, C++] The following 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

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 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 
End Namespace 'MyProject

[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.
            }
        }

    }
}

[C++] 
#using <mscorlib.dll>
#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;

__gc class MyNewQueue 
{
    // References public queues.
public:
    void SendPublic() 
    {
        MessageQueue* myQueue = new MessageQueue(S".\\myQueue");
        myQueue->Send(S"Public queue by path name.");

        return;
    }

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

        return;
    }

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

        return;
    }

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

        return;
    }

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

    // References queue journal queues.
public:
    void MonitorQueueJournal() 
    {
        MessageQueue* queueJournal = new MessageQueue(S".\\myQueue\\Journal$");
        while(true) 
        {
            Message* journalMessage = queueJournal->Receive();
            // Process the journal message.
        }
    }

    // References dead-letter queues.
public:
    void MonitorDeadLetter() 
    {
        MessageQueue* deadLetter = new MessageQueue(S".\\DeadLetter$");
        while(true) 
        {
            Message* deadMessage = deadLetter->Receive();
            // Process the dead-letter message.
        }
    }

    // References transactional dead-letter queues.
public:
    void MonitorTransactionalDeadLetter() 
    {
        MessageQueue* TxDeadLetter = new MessageQueue(S".\\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 = new MyNewQueue();

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

    return 0;
}

[Visual Basic, C#, C++] The following 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

Namespace MyProject


    ' 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


    '/ <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 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(MyProject.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
End Namespace 'MyProject

[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;
        }
    }
}

[C++] 
#using <mscorlib.dll>
#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.
__gc class Order 
{
public:
    int orderId;
    DateTime orderTime;
};    

/// <summary>
/// Provides a container class for the example.
/// </summary>
__gc class MyNewQueue 
{
public:
    //*************************************************
    // Sends an Order to a queue.
    //*************************************************
    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(S".\\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 = new MessageQueue(S".\\myQueue");

        // Set the formatter to indicate body contains an Order.
        Type* p __gc[] = new Type* __gc[1];
        p[0] = __typeof(Order);
        myQueue->Formatter = new XmlMessageFormatter( p );

        try 
        {
            // Receive and format the message. 
            Message* myMessage = myQueue->Receive(); 
            Order* myOrder = static_cast<Order*>(myMessage->Body);

            // Display message information.
            Console::WriteLine(S"Order ID: {0}", __box(myOrder->orderId));
            Console::WriteLine(S"Sent: {0}", __box(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 = new MyNewQueue();

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

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

    return 0;
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Namespace: System.Messaging

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

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

See Also

MessageQueue Members | System.Messaging Namespace | Message | DefaultPropertiesToSend | MessageQueueException | MessageQueue | Send | Peek | Receive | BeginPeek | BeginReceive | Path | Label | FormatName | QueueName | MachineName | Create

Show:
© 2014 Microsoft