You receive an error message when you perform asynchronous receive operations on a Message Queuing dependent client (816497)



The information in this article applies to:

  • Microsoft .NET Framework 1.0
  • Microsoft .NET Framework 1.0 SP1
  • Microsoft .NET Framework 1.0 SP2
  • Microsoft .NET Framework 1.0 SP3
  • Microsoft .NET Framework 1.1
  • Microsoft Message Queue Server (MSMQ) 1.0

SYMPTOMS

You may receive the following error message when you perform asynchronous receive operations on a Microsoft Message Queuing (also known as MSMQ) dependent client:
An unhandled exception of type 'System.NullReferenceException' occurred in Unknown Module. Additional information: Object reference not set to an instance of an object.

CAUSE

This problem occurs because the IAsyncResult object that is returned by the MessageQueue.BeginReceive method is garbage collected before the callback fires.

RESOLUTION

To resolve this problem, references to the IAsyncResult object for each invocation of the BeginReceive method must be kept alive until the callback is complete. If the references are not kept alive, they cannot be garbage collected.

MORE INFORMATION

To prevent IAsyncResult objects from being garbage collected, put them in an ArrayList class. The following Microsoft Visual Basic .NET code illustrates how to do so:
Public Sub EnableNotifications()
	Dim mq as new MessageQueue("server\queue")
	AddHandler mq.ReceiveCompleted, AddressOf HandleReceiveCompleted
	Dim result as IAsyncResult
	result = mq.BeginReceive()
	asyncList.Add(result) // asyncList is a global variable of type System.Collections.ArrayList()
End Sub

Public Sub HandleReceiveCompleted(ByVal sender As Object, ByVal e As ReceiveCompletedEventArgs)
	Dim m as Message
	Dim mq as MessageQueue = CType(sender, MessageQueue)
	m = mq.EndReceive(e.AsyncResult)
 // Code to handle message goes here.
End Sub
The following Microsoft Visual C# .NET code illustrates how to do so:
public void EnableNotifications()
		{
			MessageQueue mq = new MessageQueue("server\queue");
			mq.ReceiveCompleted += new ReceiveCompletedEventHandler(mq_ReceiveCompleted);
   IAsyncResult result = mq.BeginReceive();
			asyncList.Add(result); // asyncList is a global variable of type System.Collections.ArrayList()
  }

		public void mq_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
		{
			MessageQueue mq = (MessageQueue)sender;
			System.Messaging.Message m = mq.EndReceive(e.AsyncResult);
   // Code to handle message goes here.
		}

Modification Type:MajorLast Reviewed:4/20/2005
Keywords:kbprb KB816497 kbAudDeveloper