MessageQueue.BeginReceive MessageQueue.BeginReceive MessageQueue.BeginReceive MessageQueue.BeginReceive Method

定義

啟始非同步接收作業,方法是告知訊息佇列開始接收訊息,並在完成時告知事件處理常式。Initiates an asynchronous receive operation by telling Message Queuing to begin receiving a message and notify the event handler when finished.

多載

BeginReceive() BeginReceive() BeginReceive() BeginReceive()

啟始沒有逾時的非同步接收作業。作業要等到訊息可以在佇列中使用之後才算完成。Initiates an asynchronous receive operation that has no time-out. The operation is not complete until a message becomes available in the queue.

BeginReceive(TimeSpan) BeginReceive(TimeSpan) BeginReceive(TimeSpan) BeginReceive(TimeSpan)

啟始有指定逾時的非同步接收作業。在訊息可以於佇列中使用或發生逾時之後,作業才會完成。Initiates an asynchronous receive operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginReceive(TimeSpan, Object) BeginReceive(TimeSpan, Object) BeginReceive(TimeSpan, Object) BeginReceive(TimeSpan, Object)

啟始有指定逾時和指定狀態物件的非同步接收作業,會在作業的整個存留期內提供相關的資訊。Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. 在訊息可以於佇列中使用或發生逾時之後,作業才會完成。The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginReceive(TimeSpan, Object, AsyncCallback) BeginReceive(TimeSpan, Object, AsyncCallback) BeginReceive(TimeSpan, Object, AsyncCallback) BeginReceive(TimeSpan, Object, AsyncCallback)

啟始有指定逾時和指定狀態物件的非同步接收作業,會在作業的整個存留期內提供相關的資訊。Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. 這個多載會透過回呼,接收作業的事件處理常式的識別通知。This overload receives notification, through a callback, of the identity of the event handler for the operation. 在訊息可以於佇列中使用或發生逾時之後,作業才會完成。The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback) BeginReceive(TimeSpan, Cursor, Object, AsyncCallback) BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

初始化非同步接收作業,該作業具有指定的逾時,並使用指定的游標和指定的狀態物件。Initiates an asynchronous receive operation that has a specified time-out and uses a specified cursor and a specified state object. 狀態物件提供整個作業存留期的相關聯資訊。The state object provides associated information throughout the lifetime of the operation. 這個多載會透過回呼,接收作業的事件處理常式的識別通知。This overload receives notification, through a callback, of the identity of the event handler for the operation. 在訊息可以於佇列中使用或發生逾時之後,作業才會完成。The operation is not complete until either a message becomes available in the queue or the time-out occurs.

BeginReceive() BeginReceive() BeginReceive() BeginReceive()

啟始沒有逾時的非同步接收作業。作業要等到訊息可以在佇列中使用之後才算完成。Initiates an asynchronous receive operation that has no time-out. The operation is not complete until a message becomes available in the queue.

public:
 IAsyncResult ^ BeginReceive();
public IAsyncResult BeginReceive ();
member this.BeginReceive : unit -> IAsyncResult
Public Function BeginReceive () As IAsyncResult

傳回

識別傳送的非同步要求的 IAsyncResultThe IAsyncResult that identifies the posted asynchronous request.

例外狀況

存取訊息佇列方法時發生錯誤。An error occurred when accessing a Message Queuing method.

範例

下列程式碼範例會連結非同步要求。The following code example chains asynchronous requests. 它假設本機電腦上有一個稱為 "myQueue" 的佇列。It assumes there is a queue on the local computer called "myQueue". 函式會開始MyReceiveCompleted常式所處理的非同步作業。 MainThe Main function begins the asynchronous operation that is handled by the MyReceiveCompleted routine. MyReceiveCompleted處理目前的訊息, 並開始新的非同步接收作業。MyReceiveCompleted processes the current message and begins a new asynchronous receive operation.

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;
using namespace System::Threading;

ref class MyNewQueue
{
public:

   // Define static class members.
   static ManualResetEvent^ signal = gcnew ManualResetEvent( false );
   static int count = 0;

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

         // End the asynchronous receive operation.
         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;
   }
};

// Provides an entry point into the application.
//         
// This example performs asynchronous receive
// operation processing.
int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the ReceiveCompleted event.
   myQueue->ReceiveCompleted += gcnew ReceiveCompletedEventHandler( MyNewQueue::MyReceiveCompleted );

   // Begin the asynchronous receive operation.
   myQueue->BeginReceive();
   MyNewQueue::signal->WaitOne();

   // Do other work on the current thread.
   return 0;
}
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; 
		}
	}
}
Imports System.Messaging
Imports System.Threading




' Provides a container class for the example.

Public Class MyNewQueue

        ' Define static class members.
        Private Shared signal As New ManualResetEvent(False)
        Private Shared count As Integer = 0



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


        Public Shared Sub Main()
            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Add an event handler for the ReceiveCompleted event.
            AddHandler myQueue.ReceiveCompleted, AddressOf _
                MyReceiveCompleted

            ' Begin the asynchronous receive operation.
            myQueue.BeginReceive()

            signal.WaitOne()

            ' Do other work on the current thread.

            Return

        End Sub 'Main



        ' Provides an event handler for the ReceiveCompleted
        ' event.


        Private Shared Sub MyReceiveCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As ReceiveCompletedEventArgs)

            Try
                ' Connect to the queue.
                Dim mq As MessageQueue = CType([source], MessageQueue)

                ' End the asynchronous receive operation.
                Dim m As Message = _
                    mq.EndReceive(asyncResult.AsyncResult)

                count += 1
                If count = 10 Then
                    signal.Set()
                End If

                ' Restart the asynchronous receive operation.
                mq.BeginReceive()

            Catch
                ' Handle sources of MessageQueueException.

                ' Handle other exceptions.

            End Try

            Return

        End Sub 'MyReceiveCompleted

End Class 'MyNewQueue

下列程式碼範例會將非同步要求排入佇列。The following code example queues asynchronous requests. 對的呼叫BeginReceiveAsyncWaitHandle在其傳回值中使用。The call to BeginReceive uses the AsyncWaitHandle in its return value. Main常式會等待所有非同步作業完成後再結束。The Main routine waits for all asynchronous operations to be completed before exiting.

#using <system.dll>
#using <system.messaging.dll>

using namespace System;
using namespace System::Messaging;
using namespace System::Threading;

ref class MyNewQueue
{
public:

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

         // End the asynchronous receive operation.
         mq->EndReceive( asyncResult->AsyncResult );

         // Process the message here.
         Console::WriteLine( "Message received." );
      }
      catch ( MessageQueueException^ ) 
      {
         // Handle sources of MessageQueueException.
      }
      // Handle other exceptions.
      return;
   }
};

// Provides an entry point into the application.
//         
// This example performs asynchronous receive
// operation processing.
int main()
{
   // Create an instance of MessageQueue. Set its formatter.
   MessageQueue^ myQueue = gcnew MessageQueue( ".\\myQueue" );
   array<Type^>^p = gcnew array<Type^>(1);
   p[ 0 ] = String::typeid;
   myQueue->Formatter = gcnew XmlMessageFormatter( p );

   // Add an event handler for the ReceiveCompleted event.
   myQueue->ReceiveCompleted += gcnew ReceiveCompletedEventHandler( MyNewQueue::MyReceiveCompleted );

   // Define wait handles for multiple operations.
   array<WaitHandle^>^waitHandleArray = gcnew array<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 0;
}
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; 
		}
	}
}
Imports System.Messaging
Imports System.Threading


' Provides a container class for the example.

Public Class MyNewQueue


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


        Public Shared Sub Main()

            ' Create an instance of MessageQueue. Set its formatter.
            Dim myQueue As New MessageQueue(".\myQueue")
            myQueue.Formatter = New XmlMessageFormatter(New Type() _
                {GetType([String])})

            ' Add an event handler for the ReceiveCompleted event.
            AddHandler myQueue.ReceiveCompleted, AddressOf _
                MyReceiveCompleted

            ' Define wait handles for multiple operations.
            Dim waitHandleArray(10) As WaitHandle

            Dim i As Integer
            For i = 0 To 9
                ' Begin asynchronous operations.
                waitHandleArray(i) = _
                    myQueue.BeginReceive().AsyncWaitHandle
            Next i

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

            Return

        End Sub 'Main



        ' Provides an event handler for the ReceiveCompleted
        ' event.


        Private Shared Sub MyReceiveCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As ReceiveCompletedEventArgs)

            Try
                ' Connect to the queue.
                Dim mq As MessageQueue = CType([source], MessageQueue)

                ' End the asynchronous receive operation.
                Dim m As Message = _
                    mq.EndReceive(asyncResult.AsyncResult)

                ' Process the message here.
                Console.WriteLine("Message received.")

            Catch

                ' Handle sources of MessageQueueException.

                ' Handle other exceptions.

            End Try

            Return

        End Sub 'MyReceiveCompleted

End Class 'MyNewQueue

備註

在非同步處理中, 當BeginReceive已從佇列ReceiveCompleted中移除訊息時, 您可以使用來引發事件。In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message has been removed from the queue.

ReceiveCompleted如果訊息已經存在於佇列中, 也會引發。ReceiveCompleted is also raised if a message already exists in the queue.

若要BeginReceive使用, 請建立一個事件處理常式, 以處理非同步作業的結果, 並將它與您的事件委派產生關聯。To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive起始非同步接收作業;當訊息抵達佇列時, ReceiveCompleted 會透過引發事件來通知。MessageQueueBeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. 接著MessageQueue , 可以藉由呼叫EndReceive(IAsyncResult)來存取訊息。The MessageQueue can then access the message by calling EndReceive(IAsyncResult).

BeginReceive方法會立即傳回, 但是在呼叫事件處理常式之前, 非同步作業不會完成。The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.

因為BeginReceive是非同步, 所以您可以呼叫它以從佇列接收訊息, 而不會封鎖目前執行的執行緒。Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. 若要同步接收訊息, 請使用Receive方法。To synchronously receive a message, use the Receive method.

非同步作業完成後, 您可以在事件BeginPeek處理BeginReceive程式中再次呼叫或, 以繼續接收通知。Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

傳回的BeginReceive會識別方法啟動的非同步作業。 IAsyncResultThe IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. 雖然您通常不IAsyncResult會在呼叫之前EndReceive(IAsyncResult)使用此作業, 但您可以在作業的整個存留期間使用此方式。You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. 不過, 如果您啟動數個非同步作業, 您可以將IAsyncResult它們的值放在陣列中, 並指定要等候所有作業還是完成任何操作。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. 在此情況下, 您可以AsyncWaitHandle使用的屬性IAsyncResult來識別已完成的作業。In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

如果CanRead EndReceive(IAsyncResult)false, 則會引發完成事件, 但呼叫時, 將會擲回例外狀況。If CanRead is false, the completion event is raised, but an exception will be thrown when calling EndReceive(IAsyncResult).

請勿在交易中使用非同步BeginReceive呼叫。Do not use the asynchronous call BeginReceive with transactions. 如果您想要執行交易式非同步作業, 請BeginPeek呼叫, 並在您為查看作業所建立Receive的事件處理常式中放置交易和 (同步) 方法。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. 您的事件處理常式可能包含功能, 如下列C#程式碼所示。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
另請參閱

BeginReceive(TimeSpan) BeginReceive(TimeSpan) BeginReceive(TimeSpan) BeginReceive(TimeSpan)

啟始有指定逾時的非同步接收作業。在訊息可以於佇列中使用或發生逾時之後,作業才會完成。Initiates an asynchronous receive operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout);
public IAsyncResult BeginReceive (TimeSpan timeout);
member this.BeginReceive : TimeSpan -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan) As IAsyncResult

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待訊息變成可以使用的時間間隔。A TimeSpan that indicates the interval of time to wait for a message to become available.

傳回

識別傳送的非同步要求的 IAsyncResultThe IAsyncResult that identifies the posted asynchronous request.

例外狀況

timeout 參數所指定的值無效,可能是因為它表示負數。The value specified for the timeout parameter is not valid, possibly because it represents a negative number.

存取訊息佇列方法時發生錯誤。An error occurred when accessing a Message Queuing method.

範例

下列程式碼範例會建立非同步接收作業。The following code example creates an asynchronous receive operation. 此程式碼範例會建立事件處理MyReceiveCompleted程式, 並將它附加ReceiveCompleted至事件處理常式委派。The code example creates an event handler, MyReceiveCompleted, and attaches it to the ReceiveCompleted event handler delegate. 此程式碼範例會將訊息傳送至本機訊息佇列, 然後BeginReceive(TimeSpan)呼叫, 傳入10秒的超時值。The code example sends a message to a local message queue, then calls BeginReceive(TimeSpan), passing in a time-out value of ten seconds. 當引發ReceiveCompleted事件時, 事件處理常式會接收訊息, 並將訊息內文寫入畫面。When a ReceiveCompleted event is raised, the event handler receives the message and writes the message body to the screen.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if(!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();       
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the ReceiveCompleted event.
void HandleReceiveCompleted(Object^ source, ReceiveCompletedEventArgs^ e)
{
    // Connect to the queue.
    MessageQueue^ queue = (MessageQueue^)source;

    // End the asynchronous receive operation.
    Message^ msg = queue->EndReceive(e->AsyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message body: {0}", msg->Body);
    
    queue->Close();
}

int main()
{
    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    MessageQueue^ queue = nullptr;
    try
    {
        CreateQueue(".\\exampleQueue", false);

        // Connect to a queue on the local computer.
        queue = gcnew MessageQueue(".\\exampleQueue");

        // Add an event handler for the ReceiveCompleted event.
        queue->ReceiveCompleted += gcnew
            ReceiveCompletedEventHandler(HandleReceiveCompleted);

        // Send a message to the queue.
        queue->Send("Example Message");

        // Begin the asynchronous receive operation.
        queue->BeginReceive(TimeSpan::FromSeconds(10.0));

        // Simulate doing other work on the current thread.
        System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));
    }

    catch (InvalidOperationException^)
    {
        Console::WriteLine("Please install Message Queuing.");
    }

    catch (MessageQueueException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    finally
    {   
        queue->Close();
    }

}

using System;
using System.Messaging;

public class QueueExample
{
    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

        // Connect to a queue on the local computer.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // Add an event handler for the ReceiveCompleted event.
        queue.ReceiveCompleted += new 
                ReceiveCompletedEventHandler(MyReceiveCompleted);

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous receive operation.
        queue.BeginReceive(TimeSpan.FromSeconds(10.0));

        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

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

        // End the asynchronous receive operation.
        Message msg = queue.EndReceive(asyncResult.AsyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message body: {0}", (string)msg.Body);
    }
}

備註

在非同步處理中, 當BeginReceive訊息在佇列ReceiveCompleted中可供使用時, 或指定的時間間隔已過期時, 您會使用來引發事件。In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message becomes available in the queue or when the specified interval of time has expired.

ReceiveCompleted如果訊息已經存在於佇列中, 也會引發。ReceiveCompleted is also raised if a message already exists in the queue.

若要BeginReceive使用, 請建立一個事件處理常式, 以處理非同步作業的結果, 並將它與您的事件委派產生關聯。To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive起始非同步接收作業;當訊息抵達佇列時, ReceiveCompleted 會透過引發事件來通知。MessageQueueBeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. 接著MessageQueue , 可以藉由呼叫EndReceive(IAsyncResult)或使用ReceiveCompletedEventArgs來抓取結果, 來存取訊息。The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.

BeginReceive方法會立即傳回, 但是在呼叫事件處理常式之前, 非同步作業不會完成。The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.

因為BeginReceive是非同步, 所以您可以呼叫它以從佇列接收訊息, 而不會封鎖目前執行的執行緒。Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. 若要同步接收訊息, 請使用Receive方法。To synchronously receive a message, use the Receive method.

非同步作業完成後, 您可以在事件BeginPeek處理BeginReceive程式中再次呼叫或, 以繼續接收通知。Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

如果CanRead EndReceive(IAsyncResult)false, 則會引發完成事件, 但呼叫時, 將會擲回例外狀況。If CanRead is false, the completion event is raised, but an exception will be thrown when calling EndReceive(IAsyncResult).

傳回的BeginReceive會識別方法啟動的非同步作業。 IAsyncResultThe IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. 雖然您通常不IAsyncResult會在呼叫之前EndReceive(IAsyncResult)使用此作業, 但您可以在作業的整個存留期間使用此方式。You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. 不過, 如果您啟動數個非同步作業, 您可以將IAsyncResult它們的值放在陣列中, 並指定要等候所有作業還是完成任何操作。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. 在此情況下, 您可以AsyncWaitHandle使用的屬性IAsyncResult來識別已完成的作業。In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

這個多載會指定超時時間。如果timeout參數所指定的間隔過期, 這個元件就會ReceiveCompleted引發事件。This overload specifies a time-out. If the interval specified by the timeout parameter expires, this component raises the ReceiveCompleted event. 因為不存在任何訊息, 後續對的EndReceive(IAsyncResult)呼叫將會擲回例外狀況。Because no message exists, a subsequent call to EndReceive(IAsyncResult) will throw an exception.

請勿在交易中使用非同步BeginReceive呼叫。Do not use the asynchronous call BeginReceive with transactions. 如果您想要執行交易式非同步作業, 請BeginPeek呼叫, 並在您為查看作業所建立Receive的事件處理常式中放置交易和 (同步) 方法。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. 您的事件處理常式可能包含功能, 如下列C#程式碼所示。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
另請參閱

BeginReceive(TimeSpan, Object) BeginReceive(TimeSpan, Object) BeginReceive(TimeSpan, Object) BeginReceive(TimeSpan, Object)

啟始有指定逾時和指定狀態物件的非同步接收作業,會在作業的整個存留期內提供相關的資訊。Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. 在訊息可以於佇列中使用或發生逾時之後,作業才會完成。The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout, System::Object ^ stateObject);
public IAsyncResult BeginReceive (TimeSpan timeout, object stateObject);
member this.BeginReceive : TimeSpan * obj -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan, stateObject As Object) As IAsyncResult

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待訊息變成可以使用的時間間隔。A TimeSpan that indicates the interval of time to wait for a message to become available.

stateObject
Object Object Object Object

應用程式指定的狀態物件,包含與非同步作業相關的資訊。A state object, specified by the application, that contains information associated with the asynchronous operation.

傳回

識別傳送的非同步要求的 IAsyncResultThe IAsyncResult that identifies the posted asynchronous request.

例外狀況

指定給 timeout 參數的值無效。The value specified for the timeout parameter is not valid.

存取訊息佇列方法時發生錯誤。An error occurred when accessing a Message Queuing method.

範例

下列程式碼範例會建立非同步接收作業。The following code example creates an asynchronous receive operation. 此程式碼範例會建立事件處理MyReceiveCompleted程式, 並將它附加ReceiveCompleted至事件處理常式委派。The code example creates an event handler, MyReceiveCompleted, and attaches it to the ReceiveCompleted event handler delegate. 程式碼範例會將訊息傳送至本機訊息佇列, 然後呼叫BeginReceive(TimeSpan, Object), 傳入10秒的超時值和識別該特定訊息的唯一整數。The code example sends a message to a local message queue, then calls BeginReceive(TimeSpan, Object), passing in a time-out value of ten seconds and a unique integer that identifies that particular message. 當引發ReceiveCompleted事件時, 事件處理常式會接收訊息, 並將訊息內文和整數訊息識別碼寫入畫面。When a ReceiveCompleted event is raised, the event handler receives the message and writes the message body and the integer message identifier to the screen.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if(!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();       
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the ReceiveCompleted event.
void HandleReceiveCompleted(Object^ source, ReceiveCompletedEventArgs^ e)
{
    // Connect to the queue.
    MessageQueue^ queue = (MessageQueue^)source;

    // End the asynchronous receive operation.
    Message^ msg = queue->EndReceive(e->AsyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message number: {0}", e->AsyncResult->AsyncState);
    Console::WriteLine("Message body: {0}", msg->Body);

    queue->Close();
}

int main()
{
    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    MessageQueue^ queue = nullptr;

    // Represents a state object associated with each message.
    int messageNumber = 0;

    try
    {
        CreateQueue(".\\exampleQueue", false);

        // Connect to a queue on the local computer.
        queue = gcnew MessageQueue(".\\exampleQueue");

        // Add an event handler for the ReceiveCompleted event.
        queue->ReceiveCompleted += gcnew
            ReceiveCompletedEventHandler(HandleReceiveCompleted);

        // Send a message to the queue.
        queue->Send("Example Message");

        // Begin the asynchronous receive operation.
        queue->BeginReceive(TimeSpan::FromSeconds(10.0), messageNumber++);

        // Simulate doing other work on the current thread.
        System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));
    }
    catch (InvalidOperationException^)
    {
        Console::WriteLine("Please install Message Queuing.");
    }

    catch (MessageQueueException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    finally
    {   
        queue->Close();
    }
}


using System;
using System.Messaging;

public class QueueExample
{
    // Represents a state object associated with each message.
    static int messageNumber = 0;

    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

        // Connect to a queue on the local computer.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // Add an event handler for the ReceiveCompleted event.
        queue.ReceiveCompleted += new 
            ReceiveCompletedEventHandler(MyReceiveCompleted);

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous receive operation.
        queue.BeginReceive(TimeSpan.FromSeconds(10.0), messageNumber++);

        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

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

        // End the asynchronous receive operation.
        Message msg = queue.EndReceive(asyncResult.AsyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message number: {0}",
            (int)asyncResult.AsyncResult.AsyncState);
        Console.WriteLine("Message body: {0}", (string)msg.Body);
    }
}

備註

在非同步處理中, 當BeginReceive訊息在佇列ReceiveCompleted中可供使用時, 或指定的時間間隔已過期時, 您會使用來引發事件。In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message becomes available in the queue or when the specified interval of time has expired.

ReceiveCompleted如果訊息已經存在於佇列中, 也會引發。ReceiveCompleted is also raised if a message already exists in the queue.

使用此多載, 將資訊與將在作業存留期內保留的作業產生關聯。Use this overload to associate information with the operation that will be preserved throughout the operation's lifetime. 事件處理常式可以藉由查看AsyncState與作業相關聯之的屬性IAsyncResult來偵測這項資訊。The event handler can detect this information by looking at the AsyncState property of the IAsyncResult that is associated with the operation.

若要BeginReceive使用, 請建立一個事件處理常式, 以處理非同步作業的結果, 並將它與您的事件委派產生關聯。To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive起始非同步接收作業;當訊息抵達佇列時, ReceiveCompleted 會透過引發事件來通知。MessageQueueBeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. 接著MessageQueue , 可以藉由呼叫EndReceive(IAsyncResult)或使用ReceiveCompletedEventArgs來抓取結果, 來存取訊息。The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.

BeginReceive方法會立即傳回, 但是在呼叫事件處理常式之前, 非同步作業不會完成。The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.

因為BeginReceive是非同步, 所以您可以呼叫它以從佇列接收訊息, 而不會封鎖目前執行的執行緒。Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. 若要同步接收訊息, 請使用Receive方法。To synchronously receive a message, use the Receive method.

非同步作業完成後, 您可以在事件BeginPeek處理BeginReceive程式中再次呼叫或, 以繼續接收通知。Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

傳回的BeginReceive會識別方法啟動的非同步作業。 IAsyncResultThe IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. 雖然您通常不IAsyncResult會在呼叫之前EndReceive(IAsyncResult)使用此作業, 但您可以在作業的整個存留期間使用此方式。You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. 不過, 如果您啟動數個非同步作業, 您可以將IAsyncResult它們的值放在陣列中, 並指定要等候所有作業還是完成任何操作。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. 在此情況下, 您可以AsyncWaitHandle使用的屬性IAsyncResult來識別已完成的作業。In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

這個多載會指定超時和狀態物件。This overload specifies a time-out and a state object. 如果timeout參數所指定的間隔過期, 這個元件就會ReceiveCompleted引發事件。If the interval specified by the timeout parameter expires, this component raises the ReceiveCompleted event. 因為不存在任何訊息, 後續對的EndReceive(IAsyncResult)呼叫將會擲回例外狀況。Because no message exists, a subsequent call to EndReceive(IAsyncResult) will throw an exception.

狀態物件會將狀態資訊與作業相關聯。The state object associates state information with the operation. 例如, 如果您多次呼叫BeginReceive來起始多個作業, 您可以透過您所定義的個別狀態物件, 來識別每個操作。For example, if you call BeginReceive multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.

您也可以使用狀態物件在進程執行緒之間傳遞資訊。You can also use the state object to pass information across process threads. 如果執行緒已啟動, 但回呼是在非同步案例中的不同執行緒上, 則會封送處理狀態物件, 並連同事件中的資訊一起回傳。If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.

請勿在交易中使用非同步BeginReceive呼叫。Do not use the asynchronous call BeginReceive with transactions. 如果您想要執行交易式非同步作業, 請BeginPeek呼叫, 並在您為查看作業所建立Receive的事件處理常式中放置交易和 (同步) 方法。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. 您的事件處理常式可能包含功能, 如下列C#程式碼所示。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
另請參閱

BeginReceive(TimeSpan, Object, AsyncCallback) BeginReceive(TimeSpan, Object, AsyncCallback) BeginReceive(TimeSpan, Object, AsyncCallback) BeginReceive(TimeSpan, Object, AsyncCallback)

啟始有指定逾時和指定狀態物件的非同步接收作業,會在作業的整個存留期內提供相關的資訊。Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. 這個多載會透過回呼,接收作業的事件處理常式的識別通知。This overload receives notification, through a callback, of the identity of the event handler for the operation. 在訊息可以於佇列中使用或發生逾時之後,作業才會完成。The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout, System::Object ^ stateObject, AsyncCallback ^ callback);
public IAsyncResult BeginReceive (TimeSpan timeout, object stateObject, AsyncCallback callback);
member this.BeginReceive : TimeSpan * obj * AsyncCallback -> IAsyncResult
Public Function BeginReceive (timeout As TimeSpan, stateObject As Object, callback As AsyncCallback) As IAsyncResult

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待訊息變成可以使用的時間間隔。A TimeSpan that indicates the interval of time to wait for a message to become available.

stateObject
Object Object Object Object

應用程式指定的狀態物件,包含與非同步作業相關的資訊。A state object, specified by the application, that contains information associated with the asynchronous operation.

callback
AsyncCallback AsyncCallback AsyncCallback AsyncCallback

會接收非同步作業完成通知的 AsyncCallbackThe AsyncCallback that will receive the notification of the asynchronous operation completion.

傳回

識別傳送的非同步要求的 IAsyncResultThe IAsyncResult that identifies the posted asynchronous request.

例外狀況

指定給 timeout 參數的值無效。The value specified for the timeout parameter is not valid.

存取訊息佇列方法時發生錯誤。An error occurred when accessing a Message Queuing method.

範例

下列程式碼範例會建立非同步接收作業。The following code example creates an asynchronous receive operation. 此程式碼範例會將訊息傳送至本機訊息佇列, 然後BeginReceive(TimeSpan, Object, AsyncCallback)呼叫、傳入:10 秒的超時值、識別該特定訊息的唯一整數, 以及識別事件處理常式AsyncCallback 的新實例MyReceiveCompletedThe code example sends a message to a local message queue, then calls BeginReceive(TimeSpan, Object, AsyncCallback), passing in: a time-out value of ten seconds; a unique integer that identifies that particular message; and a new instance of AsyncCallback that identifies the event handler, MyReceiveCompleted. 當引發ReceiveCompleted事件時, 事件處理常式會接收訊息, 並將訊息內文和整數訊息識別碼寫入畫面。When a ReceiveCompleted event is raised, the event handler receives the message and writes the message body and the integer message identifier to the screen.

#using <System.Messaging.dll>
#using <System.dll>

using namespace System;
using namespace System::Messaging;

// Creates a new queue.
void CreateQueue(String^ queuePath, bool transactional)
{
    if (!MessageQueue::Exists(queuePath))
    {
        MessageQueue^ queue = MessageQueue::Create(queuePath, transactional);
        queue->Close();       
    }
    else
    {
        Console::WriteLine("{0} already exists.", queuePath);
    }
}

// Provides an event handler for the ReceiveCompleted event.
void HandleReceiveCompleted(IAsyncResult^ asyncResult)
{
    // Connect to the queue.
    MessageQueue^ queue = gcnew MessageQueue(".\\exampleQueue");

    // End the asynchronous receive operation.
    Message^ msg = queue->EndReceive(asyncResult);

    // Display the message information on the screen.
    Console::WriteLine("Message number: {0}", asyncResult->AsyncState);
    Console::WriteLine("Message body: {0}", msg->Body);

    queue->Close();
}

int main()
{
    // Represents a state object associated with each message.
    int messageNumber = 0;

    // Create a non-transactional queue on the local computer.
    // Note that the queue might not be immediately accessible, and
    // therefore this example might throw an exception of type
    // System.Messaging.MessageQueueException when trying to send a
    // message to the newly created queue.
    MessageQueue^ queue = nullptr;
    try
    {
        CreateQueue(".\\exampleQueue", false);

        // Connect to a queue on the local computer.
        queue = gcnew MessageQueue(".\\exampleQueue");

        // Send a message to the queue.
        queue->Send("Example Message");

        // Begin the asynchronous receive operation.
        queue->BeginReceive(TimeSpan::FromSeconds(10.0), messageNumber++,
            gcnew AsyncCallback(HandleReceiveCompleted));

        // Simulate doing other work on the current thread.
        System::Threading::Thread::Sleep(TimeSpan::FromSeconds(10.0));
    }
    catch (InvalidOperationException^)
    {
        Console::WriteLine("Please install Message Queuing.");
    }

    catch (MessageQueueException^ ex)
    {
        Console::WriteLine(ex->Message);
    }

    finally
    {   
        queue->Close();
    }
}

using System;
using System.Messaging;

public class QueueExample
{
    // Represents a state object associated with each message.
    static int messageNumber = 0;

    public static void Main()
    {
        // Create a non-transactional queue on the local computer.
        // Note that the queue might not be immediately accessible, and
        // therefore this example might throw an exception of type
        // System.Messaging.MessageQueueException when trying to send a
        // message to the newly created queue.
        CreateQueue(".\\exampleQueue", false);

        // Connect to a queue on the local computer.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // Send a message to the queue.
        queue.Send("Example Message");

        // Begin the asynchronous receive operation.
        queue.BeginReceive(TimeSpan.FromSeconds(10.0), messageNumber++,
            new AsyncCallback(MyReceiveCompleted));
			
        // Simulate doing other work on the current thread.
        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10.0));

        return;
    }

    // Creates a new queue.
    public static void CreateQueue(string queuePath, bool transactional)
    {
        if(!MessageQueue.Exists(queuePath))
        {
            MessageQueue.Create(queuePath, transactional);
        }
        else
        {
            Console.WriteLine(queuePath + " already exists.");
        }
    }

    // Provides an event handler for the ReceiveCompleted event.
    private static void MyReceiveCompleted(IAsyncResult asyncResult)
    {
        // Connect to the queue.
        MessageQueue queue = new MessageQueue(".\\exampleQueue");

        // End the asynchronous receive operation.
        Message msg = queue.EndReceive(asyncResult);

        // Display the message information on the screen.
        Console.WriteLine("Message number: {0}", (int)asyncResult.AsyncState);
        Console.WriteLine("Message body: {0}", (string)msg.Body);
    }
}

備註

當您使用這個多載時, 當佇列中有訊息可供使用時, 或當指定的時間間隔已過期時, 就會直接叫用回呼參數中指定的回呼;ReceiveCompleted事件不會引發。When you use this overload, the callback specified in the callback parameter is invoked directly when a message becomes available in the queue or when the specified interval of time has expired; the ReceiveCompleted event is not raised. 的其他BeginReceive多載會依賴此元件來ReceiveCompleted引發事件。The other overloads of BeginReceive rely on this component to raise the ReceiveCompleted event.

ReceiveCompleted如果訊息已經存在於佇列中, 也會引發。ReceiveCompleted is also raised if a message already exists in the queue.

若要BeginReceive使用, 請建立一個事件處理常式, 以處理非同步作業的結果, 並將它與您的事件委派產生關聯。To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive起始非同步接收作業;當訊息抵達佇列時, ReceiveCompleted 會透過引發事件來通知。MessageQueueBeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. 接著MessageQueue , 可以藉由呼叫EndReceive(IAsyncResult)或使用ReceiveCompletedEventArgs來抓取結果, 來存取訊息。The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.

BeginReceive方法會立即傳回, 但是在呼叫事件處理常式之前, 非同步作業不會完成。The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.

因為BeginReceive是非同步, 所以您可以呼叫它以從佇列接收訊息, 而不會封鎖目前執行的執行緒。Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. 若要同步接收訊息, 請使用Receive方法。To synchronously receive a message, use the Receive method.

非同步作業完成後, 您可以在事件BeginPeek處理BeginReceive程式中再次呼叫或, 以繼續接收通知。Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

傳回的BeginReceive會識別方法啟動的非同步作業。 IAsyncResultThe IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. 雖然您通常不IAsyncResult會在呼叫之前EndReceive(IAsyncResult)使用此作業, 但您可以在作業的整個存留期間使用此方式。You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. 不過, 如果您啟動數個非同步作業, 您可以將IAsyncResult它們的值放在陣列中, 並指定要等候所有作業還是完成任何操作。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. 在此情況下, 您可以AsyncWaitHandle使用的屬性IAsyncResult來識別已完成的作業。In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

狀態物件會將狀態資訊與作業相關聯。The state object associates state information with the operation. 例如, 如果您多次呼叫BeginReceive來起始多個作業, 您可以透過您所定義的個別狀態物件, 來識別每個操作。For example, if you call BeginReceive multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.

您也可以使用狀態物件在進程執行緒之間傳遞資訊。You can also use the state object to pass information across process threads. 如果執行緒已啟動, 但回呼是在非同步案例中的不同執行緒上, 則會封送處理狀態物件, 並連同事件中的資訊一起回傳。If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.

請勿在交易中使用非同步BeginReceive呼叫。Do not use the asynchronous call BeginReceive with transactions. 如果您想要執行交易式非同步作業, 請BeginPeek呼叫, 並在您為查看作業所建立Receive的事件處理常式中放置交易和 (同步) 方法。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. 您的事件處理常式可能包含功能, 如下列C#程式碼所示。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
另請參閱

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback) BeginReceive(TimeSpan, Cursor, Object, AsyncCallback) BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

初始化非同步接收作業,該作業具有指定的逾時,並使用指定的游標和指定的狀態物件。Initiates an asynchronous receive operation that has a specified time-out and uses a specified cursor and a specified state object. 狀態物件提供整個作業存留期的相關聯資訊。The state object provides associated information throughout the lifetime of the operation. 這個多載會透過回呼,接收作業的事件處理常式的識別通知。This overload receives notification, through a callback, of the identity of the event handler for the operation. 在訊息可以於佇列中使用或發生逾時之後,作業才會完成。The operation is not complete until either a message becomes available in the queue or the time-out occurs.

public:
 IAsyncResult ^ BeginReceive(TimeSpan timeout, System::Messaging::Cursor ^ cursor, System::Object ^ state, AsyncCallback ^ callback);
public IAsyncResult BeginReceive (TimeSpan timeout, System.Messaging.Cursor cursor, object state, AsyncCallback callback);
member this.BeginReceive : TimeSpan * System.Messaging.Cursor * obj * AsyncCallback -> IAsyncResult

參數

timeout
TimeSpan TimeSpan TimeSpan TimeSpan

TimeSpan,指出等待訊息變成可以使用的時間間隔。A TimeSpan that indicates the interval of time to wait for a message to become available.

cursor
Cursor Cursor Cursor Cursor

Cursor,保留訊息佇列中的特定位置。A Cursor that maintains a specific position in the message queue.

state
Object Object Object Object

應用程式指定的狀態物件,包含與非同步作業相關的資訊。A state object, specified by the application, that contains information associated with the asynchronous operation.

callback
AsyncCallback AsyncCallback AsyncCallback AsyncCallback

AsyncCallback,接收非同步作業的完成通知。The AsyncCallback that receives the notification of the asynchronous operation completion.

傳回

識別傳送的非同步要求的 IAsyncResultThe IAsyncResult that identifies the posted asynchronous request.

例外狀況

cursor 參數為 nullThe cursor parameter is null.

指定給 timeout 參數的值無效。The value specified for the timeout parameter is not valid.

存取訊息佇列方法時發生錯誤。An error occurred when accessing a Message Queuing method.

備註

當您使用這個多載時, 當佇列中有訊息可供使用時, 或當指定的時間間隔已過期時, 就會直接叫用回呼參數中指定的回呼;ReceiveCompleted事件不會引發。When you use this overload, the callback specified in the callback parameter is invoked directly when a message becomes available in the queue or when the specified interval of time has expired; the ReceiveCompleted event is not raised. 的其他BeginReceive多載會依賴此元件來ReceiveCompleted引發事件。The other overloads of BeginReceive rely on this component to raise the ReceiveCompleted event.

ReceiveCompleted如果訊息已經存在於佇列中, 也會引發。ReceiveCompleted is also raised if a message already exists in the queue.

若要BeginReceive使用, 請建立一個事件處理常式, 以處理非同步作業的結果, 並將它與您的事件委派產生關聯。To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive起始非同步接收作業;當訊息抵達佇列時, ReceiveCompleted 會透過引發事件來通知。MessageQueueBeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. 接著MessageQueue , 可以藉由呼叫EndReceive(IAsyncResult)或使用ReceiveCompletedEventArgs來抓取結果, 來存取訊息。The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.

BeginReceive方法會立即傳回, 但是在呼叫事件處理常式之前, 非同步作業不會完成。The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.

因為BeginReceive是非同步, 所以您可以呼叫它以從佇列接收訊息, 而不會封鎖目前執行的執行緒。Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. 若要同步接收訊息, 請使用Receive方法。To synchronously receive a message, use the Receive method.

非同步作業完成後, 您可以在事件BeginPeek處理BeginReceive程式中再次呼叫或, 以繼續接收通知。Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.

傳回的BeginReceive會識別方法啟動的非同步作業。 IAsyncResultThe IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. 雖然您通常不IAsyncResult會在呼叫之前EndReceive(IAsyncResult)使用此作業, 但您可以在作業的整個存留期間使用此方式。You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. 不過, 如果您啟動數個非同步作業, 您可以將IAsyncResult它們的值放在陣列中, 並指定要等候所有作業還是完成任何操作。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. 在此情況下, 請AsyncWaitHandle使用的屬性IAsyncResult來識別已完成的作業。In this case, use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.

狀態物件會將狀態資訊與作業相關聯。The state object associates state information with the operation. 例如, 如果您多次呼叫BeginReceive來起始多個作業, 您可以透過您所定義的個別狀態物件, 來識別每個操作。For example, if you call BeginReceive multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.

您也可以使用狀態物件在進程執行緒之間傳遞資訊。You can also use the state object to pass information across process threads. 如果執行緒已啟動, 但回呼是在非同步案例中的不同執行緒上, 則會封送處理狀態物件, 並連同事件中的資訊一起回傳。If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.

請勿在交易中使用非同步BeginReceive呼叫。Do not use the asynchronous call BeginReceive with transactions. 如果您想要執行交易式非同步作業, 請BeginPeek呼叫, 並在您為查看作業所建立Receive的事件處理常式中放置交易和 (同步) 方法。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. 您的事件處理常式可能包含功能, 如下列C#程式碼所示。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
另請參閱

適用於