Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

MessageQueue.BeginReceive Method

Initiates an asynchronous receive operation that has no time-out. The operation is not complete until a message becomes available in the queue.

Namespace:  System.Messaging
Assembly:  System.Messaging (in System.Messaging.dll)
public IAsyncResult BeginReceive()

Return Value

Type: System.IAsyncResult
The IAsyncResult that identifies the posted asynchronous request.
ExceptionCondition
MessageQueueException

An error occurred when accessing a Message Queuing method.

In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message has been removed from the queue.

ReceiveCompleted is also raised if a message already exists in the queue.

To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. The MessageQueue can then access the message by calling EndReceive(IAsyncResult).

The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.

Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. To synchronously receive a message, use the Receive method.

Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

The IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

If CanRead is false, the completion event is raised, but an exception will be thrown when calling EndReceive(IAsyncResult).

Do not use the asynchronous call BeginReceive with transactions. If you want to perform a transactional asynchronous operation, call BeginPeek, and put the transaction and the (synchronous) Receive method within the event handler you create for the peek operation. Your event handler might contain functionality as shown in the following C# code.

 myMessageQueue.BeginTransaction();
  myMessageQueue.Receive();
  myMessageQueue.CommitTransaction();

The following table shows whether this method is available in various Workgroup modes.

Workgroup mode

Available

Local computer

Yes

Local computer and direct format name

Yes

Remote computer

No

Remote computer and direct format name

Yes

The following code example chains asynchronous requests. It assumes there is a queue on the local computer called "myQueue". The Main function begins the asynchronous operation that is handled by the MyReceiveCompleted routine. MyReceiveCompleted processes the current message and begins a new asynchronous receive operation.

using System;
using System.Messaging;
using System.Threading;

namespace MyProject
{
	/// <summary> 
	/// Provides a container class for the example. 
	/// </summary> 
	public class MyNewQueue
	{
		// Define static class members. 
		static ManualResetEvent signal = new ManualResetEvent(false);
		static int count = 0;

		//************************************************** 
		// Provides an entry point into the application. 
		//		  
		// This example performs asynchronous receive 
		// operation processing. 
		//************************************************** 

		public static void Main()
		{
			// Create an instance of MessageQueue. Set its formatter.
			MessageQueue myQueue = new MessageQueue(".\\myQueue");
			myQueue.Formatter = new XmlMessageFormatter(new Type[]
				{typeof(String)});

			// Add an event handler for the ReceiveCompleted event.
			myQueue.ReceiveCompleted += 
				new ReceiveCompletedEventHandler(MyReceiveCompleted);
			
			// Begin the asynchronous receive operation.
			myQueue.BeginReceive();

			signal.WaitOne();
			
			// Do other work on the current thread. 

			return;
		}


		//*************************************************** 
		// Provides an event handler for the ReceiveCompleted 
		// event. 
		//*************************************************** 
		
		private static void MyReceiveCompleted(Object source, 
			ReceiveCompletedEventArgs asyncResult)
		{
			try
			{
				// Connect to the queue.
				MessageQueue mq = (MessageQueue)source;

				// End the asynchronous receive operation.
				Message m = mq.EndReceive(asyncResult.AsyncResult);
				
				count += 1;
				if (count == 10)
				{
					signal.Set();
				}

				// Restart the asynchronous receive operation.
				mq.BeginReceive();
			}
			catch(MessageQueueException)
			{
				// Handle sources of MessageQueueException.
			}
			
			// Handle other exceptions. 
			
			return; 
		}
	}
}

The following code example queues asynchronous requests. The call to BeginReceive uses the AsyncWaitHandle in its return value. The Main routine waits for all asynchronous operations to be completed before exiting.

using System;
using System.Messaging;
using System.Threading;

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

		//************************************************** 
		// Provides an entry point into the application. 
		//		  
		// This example performs asynchronous receive 
		// operation processing. 
		//************************************************** 

		public static void Main()
		{
			// Create an instance of MessageQueue. Set its formatter.
			MessageQueue myQueue = new MessageQueue(".\\myQueue");
			myQueue.Formatter = new XmlMessageFormatter(new Type[]
				{typeof(String)});

			// Add an event handler for the ReceiveCompleted event.
			myQueue.ReceiveCompleted += 
				new ReceiveCompletedEventHandler(MyReceiveCompleted);
			
			// Define wait handles for multiple operations.
			WaitHandle[] waitHandleArray = new WaitHandle[10];
			for(int i=0; i<10; i++)
			{
				// Begin asynchronous operations.
				waitHandleArray[i] = 
					myQueue.BeginReceive().AsyncWaitHandle;
			}

			// Specify to wait for all operations to return.
			WaitHandle.WaitAll(waitHandleArray);

			return;
		}


		//*************************************************** 
		// Provides an event handler for the ReceiveCompleted 
		// event. 
		//*************************************************** 
		
		private static void MyReceiveCompleted(Object source, 
			ReceiveCompletedEventArgs asyncResult)
		{
			try
			{
				// Connect to the queue.
				MessageQueue mq = (MessageQueue)source;

				// End the asynchronous receive operation.
				Message m = mq.EndReceive(asyncResult.AsyncResult);
		
				// Process the message here.
				Console.WriteLine("Message received.");

			}
			catch(MessageQueueException)
			{
				// Handle sources of MessageQueueException.
			}
			
			// Handle other exceptions. 
			
			return; 
		}
	}
}

.NET Framework

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

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.