Home   |   QuickStart Welcome   |   ASP.NET   |   Web Services   |   How Do I...?   
  |   I want my samples in...      

How Do I...? Common Tasks QuickStart Tutorial

How Do I...Receive asynchronously?



Message queuing makes it easy for application developers to communicate with application programs quickly and reliably by sending and receiving messages. Messaging provides you with guaranteed message delivery and a robust, fail-safe way to carry out many of your business processes.

The MessageQueue component allows you to easily incorporate message-based communication into your applications. Using this component and its associated language features, you can send and receive messages, explore existing queues, create and delete queues, and perform a variety of other operations using a simple programming model.

The sample illustrates how to use the MessageQueue component to watch a message queue for arrival of new messages. To run the sample you have to have Message Queuing installed on your system. The sample is a command-line application that takes one command-line argument. The argument is the name of a public message queue on your local machine. For example you can run it as follows:
> MQAsync.exe MyQueue


Now, use the MQSend sample to send a message to the MyQueue queue. The sample application will be notified when the message arrives at the queue and will output the message to the console.

In its simplest form, asynchronously receiving a message from a message queue involves:
  1. Creating an instance of the MessageQueue component, and setting its Path property and the formatter:

    		
    MessageQueue mq = new MessageQueue(".\\MyQueue");
    ((XmlMessageFormatter)mq.Formatter).TargetTypeNames = new string[]{"System.String"};
    
    
    C#


  2. Setting up an event handler:

    		
    mq.ReceiveCompleted += new ReceiveCompletedEventHandler(OnReceiveCompleted);
    
    C#


  3. Implementing an event handler:

    		
    public static void OnReceiveCompleted(Object source, ReceiveCompletedEventArgs asyncResult){
        MessageQueue mq = (MessageQueue)source;
        Message m = mq.EndReceive(asyncResult.AsyncResult);
        Console.WriteLine("Message: " + (string)m.Body);
        mq.BeginReceive();
    }
    
    C#


  4. Calling BeginReceive to start an asynchronous receive operation:

    		
    mq.BeginReceive();
    
    C#




Please note that BeginReceive will receive only one message. If you want to keep receiving messages, you have to call BeginReceive again (see the event handler implementation in step 3).

Example

VB MQAsync.exe
View Source
[This sample can be found at C:\DevFusion.Data\legacy\quickstart.developerfusion.co.uk\QuickStart\howto\samples\Services\MessageQueue\MQAsync\]



Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2004 Microsoft Corporation. All rights reserved.