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:
- Creating an instance of the MessageQueue component, and setting its Path property and the formatter:
Dim mq As MessageQueue = New MessageQueue(".\MyQueue")
Dim formatter As XmlMessageFormatter = CType(mq.Formatter,XmlMessageFormatter)
formatter.TargetTypeNames = new String(){"System.String"}
VB
|
- Setting up an event handler:
AddHandler mq.ReceiveCompleted, New ReceiveCompletedEventHandler(AddressOf OnReceiveCompleted)
VB
|
- Implementing an event handler:
Public Shared Sub OnReceiveCompleted(source As Object, asyncResult As ReceiveCompletedEventArgs)
Dim mq As MessageQueue = CType(source,MessageQueue)
Dim m As Message = mq.EndReceive(asyncResult.AsyncResult)
Console.WriteLine("Message: " + CStr(m.Body))
mq.BeginReceive()
End sub
VB
|
- Calling BeginReceive to start an asynchronous receive operation:
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
[This sample can be found at H:\Home\WU_000036_efe47225c86ca62f325a01d8519bc002\Webs\aspnet.sk\quickstarts\QuickStartv20\howto\samples\Services\MessageQueue\MQAsync\
To build this sample, open the SDK command prompt and navigate to the above path. Build the sample using the build tool msbuild
passing the solution file as the first parameter: msbuild mySample.sln. The compiled executable will be found in the sub directory \bin
directory.]
Microsoft .NET Framework SDK QuickStart Tutorials Version 2.0
Copyright � 2005 Microsoft Corporation. All rights reserved.
|