語言

MessageQueue.BeginReceive 方法

定義

透過告訴訊息排隊開始接收訊息,並在完成後通知事件處理程序,啟動非同步接收操作。

多載

名稱 Description
BeginReceive()

啟動一個無逾時的非同步接收操作。直到訊息在隊列中可用時,操作才算完成。

BeginReceive(TimeSpan)

啟動一個具有指定逾時的非同步接收操作。該操作直到訊息在隊列中可用或逾時發生時才算完成。

BeginReceive(TimeSpan, Object)

啟動一個非同步接收操作,該操作具有指定的逾時時間和指定的狀態物件,該物件在整個操作的生命週期中提供相關資訊。 該操作直到訊息在隊列中可用或逾時發生時才算完成。

BeginReceive(TimeSpan, Object, AsyncCallback)

啟動一個非同步接收操作,該操作具有指定的逾時時間和指定的狀態物件,該物件在整個操作的生命週期中提供相關資訊。 此過載會透過回調接收該操作事件處理者的身份通知。 該操作直到訊息在隊列中可用或逾時發生時才算完成。

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

啟動非同步接收操作,該操作有指定的逾時時間,並使用指定的游標與狀態物件。 狀態物件在操作的整個生命週期中提供相關資訊。 此過載會透過回調接收該操作事件處理者的身份通知。 該操作直到訊息在隊列中可用或逾時發生時才算完成。

BeginReceive()

啟動一個無逾時的非同步接收操作。直到訊息在隊列中可用時,操作才算完成。

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

傳回

那 IAsyncResult 個是識別非同步請求的。

例外狀況

存取訊息佇列方法時發生錯誤。

範例

以下程式碼範例串接非同步請求。 它假設本地電腦上有一個叫做「myQueue」的佇列。 該 Main 函式開始 MyReceiveCompleted 由例程處理的非同步操作。 MyReceiveCompleted 處理目前訊息並開始新的非同步接收操作。

#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



        ' 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

End Class

以下程式碼範例用於排隊非同步請求。 呼叫 的 BeginReceive 在回傳值中使用 。AsyncWaitHandle Main例程會等待所有非同步操作完成後才退出。

#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



        ' 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

End Class

備註

在非同步處理中,當訊息從佇列中移除時,你會用 BeginReceive 來提出 ReceiveCompleted 事件。

ReceiveCompleted 若隊列中已有訊息,也會被提出。

使用 BeginReceive,建立一個事件處理程序,處理非同步操作的結果,並將其與你的事件代理關聯。 BeginReceive啟動非同步接收操作;透過事件的提出MessageQueue,當訊息抵達佇列時,會ReceiveCompleted被通知。 接著可以透過 MessageQueue 呼叫 EndReceive(IAsyncResult)來存取該訊息。

該方法會 BeginReceive 立即回傳,但非同步操作直到事件處理器被呼叫後才會完成。

因為 BeginReceive 是非同步的,你可以呼叫它來接收來自佇列的訊息,而不會阻塞目前執行緒。 要同步接收訊息,請使用該 Receive 方法。

非同步操作完成後,你可以呼叫 BeginPeek 或 BeginReceive 再次呼叫事件處理程序,持續接收通知。

IAsyncResult that BeginReceive 回傳標示方法啟動的非同步操作。 你可以在整個運作期間使用這個 IAsyncResult 功能,但通常不會 EndReceive(IAsyncResult) 在被叫到之前使用。 不過,如果你啟動多個非同步操作,可以將它們的值放入 IAsyncResult 陣列,並指定是等待所有操作或任何操作完成。 在這種情況下,你用 AsyncWaitHandle 的 IAsyncResult 屬性來識別已完成的操作。

若 CanRead , false則會觸發完結事件,但呼叫 EndReceive(IAsyncResult)時會拋出例外。

不要在交易中使用非同步呼叫 BeginReceive 。 如果你想執行交易非同步操作,呼叫 BeginPeek,並將交易和(同步) Receive 方法放入你為窺視操作建立的事件處理程序中。 你的事件處理器可能包含以下 C# 程式碼所示的功能。

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

下表顯示此方法是否可在多種工作群組模式中使用。

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

BeginReceive(TimeSpan)

啟動一個具有指定逾時的非同步接收操作。該操作直到訊息在隊列中可用或逾時發生時才算完成。

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

A TimeSpan 表示等待訊息可用的時間間隔。

傳回

那 IAsyncResult 個是識別非同步請求的。

例外狀況

參數指定的 timeout 值不有效,可能是因為它代表負數。

存取訊息佇列方法時發生錯誤。

範例

以下程式碼範例建立非同步接收操作。 程式碼範例建立一個事件處理器, MyReceiveCompleted並將其附加到 ReceiveCompleted 事件處理代理。 範例程式碼將訊息傳送到本地訊息佇列,然後呼叫 BeginReceive(TimeSpan),並以十秒的逾時值進行。 當 ReceiveCompleted 事件被提出時,事件處理器會接收訊息並將訊息內容寫入螢幕。

#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 事件。

ReceiveCompleted 若隊列中已有訊息,也會被提出。

使用 BeginReceive,建立一個事件處理程序,處理非同步操作的結果,並將其與你的事件代理關聯。 BeginReceive啟動非同步接收操作;透過事件的提出MessageQueue,當訊息抵達佇列時,會ReceiveCompleted被通知。 接著,他們 MessageQueue 可以透過呼叫 EndReceive(IAsyncResult) 或使用 ReceiveCompletedEventArgs. 來存取該訊息。

該方法會 BeginReceive 立即回傳,但非同步操作直到事件處理器被呼叫後才會完成。

因為 BeginReceive 是非同步的,你可以呼叫它來接收來自佇列的訊息,而不會阻塞目前執行緒。 要同步接收訊息,請使用該 Receive 方法。

非同步操作完成後,你可以呼叫 BeginPeek 或 BeginReceive 再次呼叫事件處理程序,持續接收通知。

若 CanRead , false則會觸發完結事件,但呼叫 EndReceive(IAsyncResult)時會拋出例外。

IAsyncResult that BeginReceive 回傳標示方法啟動的非同步操作。 你可以在整個運作期間使用這個 IAsyncResult 功能,但通常不會 EndReceive(IAsyncResult) 在被叫到之前使用。 不過,如果你啟動多個非同步操作,可以將它們的值放入 IAsyncResult 陣列,並指定是等待所有操作或任何操作完成。 在這種情況下,你用 AsyncWaitHandle 的 IAsyncResult 屬性來識別已完成的操作。

此過載指定了逾時。若參數指定的 timeout 區間結束,該元件會觸發事件 ReceiveCompleted 。 由於沒有訊息存在,後續呼叫 會 EndReceive(IAsyncResult) 拋出例外。

不要在交易中使用非同步呼叫 BeginReceive 。 如果你想執行交易非同步操作,呼叫 BeginPeek,並將交易和(同步) Receive 方法放入你為窺視操作建立的事件處理程序中。 你的事件處理器可能包含以下 C# 程式碼所示的功能。

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

下表顯示此方法是否可在多種工作群組模式中使用。

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

BeginReceive(TimeSpan, Object)

啟動一個非同步接收操作,該操作具有指定的逾時時間和指定的狀態物件,該物件在整個操作的生命週期中提供相關資訊。 該操作直到訊息在隊列中可用或逾時發生時才算完成。

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

A TimeSpan 表示等待訊息可用的時間間隔。

stateObject
Object

由應用程式指定的狀態物件,包含與非同步操作相關的資訊。

傳回

那 IAsyncResult 個是識別非同步請求的。

例外狀況

為 timeout 參數指定的值無效。

存取訊息佇列方法時發生錯誤。

範例

以下程式碼範例建立非同步接收操作。 程式碼範例建立一個事件處理器, MyReceiveCompleted並將其附加到 ReceiveCompleted 事件處理代理。 程式碼範例是將訊息傳送到本地訊息佇列,然後呼叫 BeginReceive(TimeSpan, Object),並輸入一個十秒的逾時值及一個唯一識別該訊息的整數。 當 ReceiveCompleted 事件被提出時,事件處理器會接收訊息並將訊息主體及整數訊息識別碼寫入螢幕。

#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 事件。

ReceiveCompleted 若隊列中已有訊息,也會被提出。

利用此超載將資訊與作業關聯,並在作業整個運作期間被保留。 事件處理器可以透過查看 AsyncState 與該操作相關的屬性 IAsyncResult 來偵測這些資訊。

使用 BeginReceive,建立一個事件處理程序,處理非同步操作的結果,並將其與你的事件代理關聯。 BeginReceive啟動非同步接收操作;透過事件的提出MessageQueue,當訊息抵達佇列時,會ReceiveCompleted被通知。 接著,他們 MessageQueue 可以透過呼叫 EndReceive(IAsyncResult) 或使用 ReceiveCompletedEventArgs. 來存取該訊息。

該方法會 BeginReceive 立即回傳,但非同步操作直到事件處理器被呼叫後才會完成。

因為 BeginReceive 是非同步的,你可以呼叫它來接收來自佇列的訊息,而不會阻塞目前執行緒。 要同步接收訊息,請使用該 Receive 方法。

非同步操作完成後,你可以呼叫 BeginPeek 或 BeginReceive 再次呼叫事件處理程序,持續接收通知。

IAsyncResult that BeginReceive 回傳標示方法啟動的非同步操作。 你可以在整個運作期間使用這個 IAsyncResult 功能,但通常不會 EndReceive(IAsyncResult) 在被叫到之前使用。 不過,如果你啟動多個非同步操作,可以將它們的值放入 IAsyncResult 陣列,並指定是等待所有操作或任何操作完成。 在這種情況下,你用 AsyncWaitHandle 的 IAsyncResult 屬性來識別已完成的操作。

此過載指定逾時與狀態物件。 若參數指定的 timeout 區間結束,該元件會觸發事件 ReceiveCompleted 。 由於沒有訊息存在,後續呼叫 會 EndReceive(IAsyncResult) 拋出例外。

狀態物件將狀態資訊與操作關聯起來。 例如,如果你多次呼叫 BeginReceive 以啟動多個操作,你可以透過你定義的獨立狀態物件來識別每個操作。

你也可以用狀態物件在程序執行緒間傳遞資訊。 如果執行緒啟動但回調在不同執行緒,且在非同步情境下,狀態物件會被封組並連同事件資訊一併傳回。

不要在交易中使用非同步呼叫 BeginReceive 。 如果你想執行交易非同步操作,呼叫 BeginPeek,並將交易和(同步) Receive 方法放入你為窺視操作建立的事件處理程序中。 你的事件處理器可能包含以下 C# 程式碼所示的功能。

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

下表顯示此方法是否可在多種工作群組模式中使用。

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

BeginReceive(TimeSpan, Object, AsyncCallback)

啟動一個非同步接收操作,該操作具有指定的逾時時間和指定的狀態物件,該物件在整個操作的生命週期中提供相關資訊。 此過載會透過回調接收該操作事件處理者的身份通知。 該操作直到訊息在隊列中可用或逾時發生時才算完成。

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

A TimeSpan 表示等待訊息可用的時間間隔。

stateObject
Object

由應用程式指定的狀態物件,包含與非同步操作相關的資訊。

callback
AsyncCallback

然後 AsyncCallback 會收到非同步操作完成的通知。

傳回

那 IAsyncResult 個是識別非同步請求的。

例外狀況

為 timeout 參數指定的值無效。

存取訊息佇列方法時發生錯誤。

範例

以下程式碼範例建立非同步接收操作。 範例程式碼將訊息傳送至本地訊息佇列,然後呼叫 BeginReceive(TimeSpan, Object, AsyncCallback),傳遞:逾時值為十秒;一個唯一用來識別該訊息的整數;以及一個新的實例AsyncCallback,識別事件處理程序。 MyReceiveCompleted 當 ReceiveCompleted 事件被提出時,事件處理器會接收訊息並將訊息主體及整數訊息識別碼寫入螢幕。

#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 事件不會被提及。 其他過載BeginReceive則依賴這個組件來提升事件。ReceiveCompleted

ReceiveCompleted 若隊列中已有訊息,也會被提出。

使用 BeginReceive,建立一個事件處理程序,處理非同步操作的結果,並將其與你的事件代理關聯。 BeginReceive啟動非同步接收操作;透過事件的提出MessageQueue,當訊息抵達佇列時,會ReceiveCompleted被通知。 接著,他們 MessageQueue 可以透過呼叫 EndReceive(IAsyncResult) 或使用 ReceiveCompletedEventArgs. 來存取該訊息。

該方法會 BeginReceive 立即回傳,但非同步操作直到事件處理器被呼叫後才會完成。

因為 BeginReceive 是非同步的,你可以呼叫它來接收來自佇列的訊息,而不會阻塞目前執行緒。 要同步接收訊息,請使用該 Receive 方法。

非同步操作完成後,你可以呼叫 BeginPeek 或 BeginReceive 再次呼叫事件處理程序,持續接收通知。

IAsyncResult that BeginReceive 回傳標示方法啟動的非同步操作。 你可以在整個運作期間使用這個 IAsyncResult 功能,但通常不會 EndReceive(IAsyncResult) 在被叫到之前使用。 不過,如果你啟動多個非同步操作,可以將它們的值放入 IAsyncResult 陣列,並指定是等待所有操作或任何操作完成。 在這種情況下,你用 AsyncWaitHandle 的 IAsyncResult 屬性來識別已完成的操作。

狀態物件將狀態資訊與操作關聯起來。 例如,如果你多次呼叫 BeginReceive 以啟動多個操作,你可以透過你定義的獨立狀態物件來識別每個操作。

你也可以用狀態物件在程序執行緒間傳遞資訊。 如果執行緒啟動但回調在不同執行緒,且在非同步情境下,狀態物件會被封組並連同事件資訊一併傳回。

不要在交易中使用非同步呼叫 BeginReceive 。 如果你想執行交易非同步操作,呼叫 BeginPeek,並將交易和(同步) Receive 方法放入你為窺視操作建立的事件處理程序中。 你的事件處理器可能包含以下 C# 程式碼所示的功能。

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

下表顯示此方法是否可在多種工作群組模式中使用。

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

啟動非同步接收操作,該操作有指定的逾時時間,並使用指定的游標與狀態物件。 狀態物件在操作的整個生命週期中提供相關資訊。 此過載會透過回調接收該操作事件處理者的身份通知。 該操作直到訊息在隊列中可用或逾時發生時才算完成。

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
Public Function BeginReceive (timeout As TimeSpan, cursor As Cursor, state As Object, callback As AsyncCallback) As IAsyncResult

參數

timeout
TimeSpan

A TimeSpan 表示等待訊息可用的時間間隔。

cursor
Cursor

A Cursor 在訊息佇列中維持特定位置。

state
Object

由應用程式指定的狀態物件,包含與非同步操作相關的資訊。

callback
AsyncCallback

該 AsyncCallback 該接收非同步操作完成的通知。

傳回

那 IAsyncResult 個是識別非同步請求的。

例外狀況

參數 cursor 為 null。

為 timeout 參數指定的值無效。

存取訊息佇列方法時發生錯誤。

備註

當你使用這種超載時,當訊息在隊列中可用或指定時間間隔結束時,會直接呼叫回調參數中指定的回調; ReceiveCompleted 事件不會被提及。 其他過載BeginReceive則依賴這個組件來提升事件。ReceiveCompleted

ReceiveCompleted 若隊列中已有訊息,也會被提出。

使用 BeginReceive,建立一個事件處理程序,處理非同步操作的結果,並將其與你的事件代理關聯。 BeginReceive啟動非同步接收操作;透過事件的提出MessageQueue,當訊息抵達佇列時,會ReceiveCompleted被通知。 接著,他們 MessageQueue 可以透過呼叫 EndReceive(IAsyncResult) 或使用 ReceiveCompletedEventArgs. 來存取該訊息。

該方法會 BeginReceive 立即回傳,但非同步操作直到事件處理器被呼叫後才會完成。

因為 BeginReceive 是非同步的,你可以呼叫它來接收來自佇列的訊息,而不會阻塞目前執行緒。 要同步接收訊息,請使用該 Receive 方法。

非同步操作完成後,你可以呼叫 BeginPeek 或 BeginReceive 再次呼叫事件處理程序,持續接收通知。

IAsyncResult that BeginReceive 回傳標示方法啟動的非同步操作。 你可以在整個運作期間使用這個 IAsyncResult 功能,但通常不會 EndReceive(IAsyncResult) 在被叫到之前使用。 不過,如果你啟動多個非同步操作,可以將它們的值放入 IAsyncResult 陣列,並指定是等待所有操作或任何操作完成。 此時,利用 AsyncWaitHandle 屬性 IAsyncResult 來識別已完成的操作。

狀態物件將狀態資訊與操作關聯起來。 例如,如果你多次呼叫 BeginReceive 以啟動多個操作,你可以透過你定義的獨立狀態物件來識別每個操作。

你也可以用狀態物件在程序執行緒間傳遞資訊。 如果執行緒啟動但回調在不同執行緒,且在非同步情境下,狀態物件會被封組並連同事件資訊一併傳回。

不要在交易中使用非同步呼叫 BeginReceive 。 如果你想執行交易非同步操作,呼叫 BeginPeek,並將交易和(同步) Receive 方法放入你為窺視操作建立的事件處理程序中。 你的事件處理器可能包含以下 C# 程式碼所示的功能。

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

下表顯示此方法是否可在多種工作群組模式中使用。

工作群組模式 Available
本機電腦 Yes
本地電腦與直接格式名稱 Yes
遠端電腦 No
遠端電腦與直接格式名稱 Yes

另請參閱

適用於

執行緒安全性

這個方法並不安全於執行緒。