MessageQueue.BeginReceive メソッド

定義

メッセージの受信を開始し、完了したときにイベント ハンドラーに通知するようにメッセージ キューに指示して、非同期の受信操作を実行します。

オーバーロード

BeginReceive()

タイムアウトのない非同期の受信操作を実行します。この操作は、キューのメッセージが利用可能になるまで完了しません。

BeginReceive(TimeSpan)

指定したタイムアウトのある非同期の受信操作を実行します。この操作は、メッセージをキューで使用できるようになるか、タイムアウトが発生するまで完了しません。

BeginReceive(TimeSpan, Object)

指定したタイムアウトと指定した状態オブジェクトを持つ非同期の受信操作を実行します。状態オブジェクトは、操作の有効期間を通じて関連付けられた情報を提供します。 この操作は、メッセージをキューで使用できるようになるか、タイムアウトが発生するまで完了しません。

BeginReceive(TimeSpan, Object, AsyncCallback)

指定したタイムアウトと指定した状態オブジェクトを持つ非同期の受信操作を実行します。状態オブジェクトは、操作の有効期間を通じて関連付けられた情報を提供します。 このオーバーロードは、コールバックを通じて操作のイベント ハンドラー ID の通知を受信します。 この操作は、メッセージをキューで使用できるようになるか、タイムアウトが発生するまで完了しません。

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

指定したタイムアウトがあり、指定したカーソルおよび状態オブジェクトを使用する非同期の受信操作を実行します。 状態オブジェクトは、操作の有効期間を通じて、関連付けられた情報を提供します。 このオーバーロードは、コールバックを通じて操作のイベント ハンドラー ID の通知を受信します。 この操作は、メッセージをキューで使用できるようになるか、タイムアウトが発生するまで完了しません。

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

非同期操作が完了したら、イベント ハンドラーで または BeginReceive をもう一度呼び出BeginPeekして、通知を受信し続けることができます。

IAsyncResultを返す BeginReceive は、メソッドが開始した非同期操作を識別します。 これは IAsyncResult 、操作の有効期間中は使用できますが、通常は が呼び出されるまで EndReceive(IAsyncResult) 使用しません。 ただし、複数の非同期操作を開始する場合は、それらの値を IAsyncResult 配列に配置し、すべての操作または任意の操作が完了するまで待機するかどうかを指定できます。 この場合は、 の IAsyncResult プロパティをAsyncWaitHandle使用して、完了した操作を識別します。

falseの場合CanRead、完了イベントが発生しますが、 を呼び出EndReceive(IAsyncResult)すと例外がスローされます。

トランザクションで非同期呼び出し BeginReceive を使用しないでください。 トランザクション非同期操作を実行する場合は、 を呼び出 BeginPeekし、ピーク操作用に作成したイベント ハンドラー内にトランザクションと (同期) Receive メソッドを配置します。 イベント ハンドラーには、次の C# コードに示すように機能が含まれている場合があります。

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

次の表は、このメソッドがさまざまなワークグループ モードで使用できるかどうかを示しています。

ワークグループ モード 利用可能
ローカル コンピューター はい
ローカル コンピューターと直接形式の名前 はい
リモート コンピューター いいえ
リモート コンピューターと直接形式の名前 はい

こちらもご覧ください

適用対象

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

メッセージを使用できるようになるまでの待機時間を示す TimeSpan

戻り値

ポストされた非同期要求を識別する IAsyncResult

例外

timeout パラメーターに指定された値が無効です。負数の可能性があります。

メッセージ キューのメソッドにアクセスしたときにエラーが発生しました。

次のコード例では、非同期の受信操作を作成します。 このコード例では、イベント ハンドラー を作成し、 MyReceiveCompletedそれをイベント ハンドラー デリゲートに ReceiveCompleted アタッチします。 このコード例では、ローカル メッセージ キューにメッセージを送信し、 を呼び出 BeginReceive(TimeSpan)して、タイムアウト値 10 秒を渡します。 イベントが 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

非同期操作が完了したら、イベント ハンドラーで または BeginReceive をもう一度呼び出BeginPeekして、通知を受信し続けることができます。

falseの場合CanRead、完了イベントが発生しますが、 を呼び出EndReceive(IAsyncResult)すと例外がスローされます。

IAsyncResultを返す BeginReceive は、メソッドが開始した非同期操作を識別します。 これは IAsyncResult 、操作の有効期間中は使用できますが、通常は が呼び出されるまで EndReceive(IAsyncResult) 使用しません。 ただし、複数の非同期操作を開始する場合は、それらの値を IAsyncResult 配列に配置し、すべての操作または任意の操作が完了するまで待機するかどうかを指定できます。 この場合は、 の IAsyncResult プロパティをAsyncWaitHandle使用して、完了した操作を識別します。

このオーバーロードは、タイムアウトを指定します。パラメーターで指定された間隔の有効期限が timeout 切れると、このコンポーネントは イベントを ReceiveCompleted 発生させます。 メッセージが存在しないため、後続の を EndReceive(IAsyncResult) 呼び出すと例外がスローされます。

トランザクションで非同期呼び出し BeginReceive を使用しないでください。 トランザクション非同期操作を実行する場合は、 を呼び出 BeginPeekし、ピーク操作用に作成したイベント ハンドラー内にトランザクションと (同期) Receive メソッドを配置します。 イベント ハンドラーには、次の C# コードに示すように機能が含まれている場合があります。

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

次の表は、このメソッドがさまざまなワークグループ モードで使用できるかどうかを示しています。

ワークグループ モード 利用可能
ローカル コンピューター はい
ローカル コンピューターと直接形式の名前 はい
リモート コンピューター いいえ
リモート コンピューターと直接形式の名前 はい

こちらもご覧ください

適用対象

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

メッセージを使用できるようになるまでの待機時間を示す TimeSpan

stateObject
Object

非同期操作に関連付けられている情報を保持する状態オブジェクト。アプリケーションで指定します。

戻り値

ポストされた非同期要求を識別する IAsyncResult

例外

timeout パラメーターに指定された値は無効です。

メッセージ キューのメソッドにアクセスしたときにエラーが発生しました。

次のコード例では、非同期の受信操作を作成します。 このコード例では、イベント ハンドラー を作成し、 MyReceiveCompletedそれをイベント ハンドラー デリゲートに ReceiveCompleted アタッチします。 このコード例では、ローカル メッセージ キューにメッセージを送信し、 を呼び出 BeginReceive(TimeSpan, Object)して、10 秒のタイムアウト値と、その特定のメッセージを識別する一意の整数を渡します。 イベントが 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 は、メッセージがキューに既に存在する場合にも発生します。

このオーバーロードを使用して、操作の有効期間中保持される操作に情報を関連付けます。 イベント ハンドラーは、操作に関連付けられている の IAsyncResult プロパティをAsyncState調べることで、この情報を検出できます。

を使用 BeginReceiveするには、非同期操作の結果を処理し、それをイベント デリゲートに関連付けるイベント ハンドラーを作成します。 BeginReceive 非同期受信操作を開始します。 MessageQueue は、メッセージがキューに到着したときに、イベントの ReceiveCompleted 発生によって通知されます。 MessageQueue次に、 を呼び出EndReceive(IAsyncResult)すか、 を使用して結果を取得することで、メッセージにReceiveCompletedEventArgsアクセスできます。

メソッドは BeginReceive 直ちにを返しますが、非同期操作はイベント ハンドラーが呼び出されるまで完了しません。

は非同期であるため BeginReceive 、現在の実行スレッドをブロックすることなく、それを呼び出してキューからメッセージを受信できます。 メッセージを同期的に受信するには、 メソッドを使用します Receive

非同期操作が完了したら、イベント ハンドラーで または BeginReceive をもう一度呼び出BeginPeekして、通知を受信し続けることができます。

IAsyncResultを返す BeginReceive は、メソッドが開始した非同期操作を識別します。 これは IAsyncResult 、操作の有効期間中は使用できますが、通常は が呼び出されるまで EndReceive(IAsyncResult) 使用しません。 ただし、複数の非同期操作を開始する場合は、それらの値を IAsyncResult 配列に配置し、すべての操作または任意の操作が完了するまで待機するかどうかを指定できます。 この場合は、 の IAsyncResult プロパティをAsyncWaitHandle使用して、完了した操作を識別します。

このオーバーロードは、タイムアウトと状態オブジェクトを指定します。 パラメーターで指定された間隔の有効期限が timeout 切れると、このコンポーネントは イベントを ReceiveCompleted 発生させます。 メッセージが存在しないため、後続の を EndReceive(IAsyncResult) 呼び出すと例外がスローされます。

state オブジェクトは、状態情報を操作に関連付けます。 たとえば、複数回呼び出 BeginReceive して複数の操作を開始する場合は、定義した個別の状態オブジェクトを使用して各操作を識別できます。

状態オブジェクトを使用して、プロセス スレッド間で情報を渡すこともできます。 スレッドが開始されたが、非同期シナリオでコールバックが別のスレッド上にある場合、状態オブジェクトはマーシャリングされ、イベントからの情報と共に返されます。

トランザクションで非同期呼び出し BeginReceive を使用しないでください。 トランザクション非同期操作を実行する場合は、 を呼び出 BeginPeekし、ピーク操作用に作成したイベント ハンドラー内にトランザクションと (同期) Receive メソッドを配置します。 イベント ハンドラーには、次の C# コードに示すように機能が含まれている場合があります。

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

次の表は、このメソッドがさまざまなワークグループ モードで使用できるかどうかを示しています。

ワークグループ モード 利用可能
ローカル コンピューター はい
ローカル コンピューターと直接形式の名前 はい
リモート コンピューター いいえ
リモート コンピューターと直接形式の名前 はい

こちらもご覧ください

適用対象

BeginReceive(TimeSpan, Object, AsyncCallback)

指定したタイムアウトと指定した状態オブジェクトを持つ非同期の受信操作を実行します。状態オブジェクトは、操作の有効期間を通じて関連付けられた情報を提供します。 このオーバーロードは、コールバックを通じて操作のイベント ハンドラー ID の通知を受信します。 この操作は、メッセージをキューで使用できるようになるか、タイムアウトが発生するまで完了しません。

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

stateObject
Object

非同期操作に関連付けられている情報を保持する状態オブジェクト。アプリケーションで指定します。

callback
AsyncCallback

非同期操作の完了通知を受信する AsyncCallback

戻り値

ポストされた非同期要求を識別する IAsyncResult

例外

timeout パラメーターに指定された値は無効です。

メッセージ キューのメソッドにアクセスしたときにエラーが発生しました。

次のコード例では、非同期の受信操作を作成します。 このコード例では、ローカル メッセージ キューにメッセージを送信し、 を呼び出BeginReceive(TimeSpan, Object, AsyncCallback)します。10 秒のタイムアウト値、その特定のメッセージを識別する一意の整数、およびイベント ハンドラーMyReceiveCompletedを識別する のAsyncCallback新しいインスタンスを渡します。 イベントが 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

非同期操作が完了したら、イベント ハンドラーで または BeginReceive をもう一度呼び出BeginPeekして、通知を受信し続けることができます。

IAsyncResultを返す BeginReceive は、メソッドが開始した非同期操作を識別します。 これは IAsyncResult 、操作の有効期間中は使用できますが、通常は が呼び出されるまで EndReceive(IAsyncResult) 使用しません。 ただし、複数の非同期操作を開始する場合は、それらの値を IAsyncResult 配列に配置し、すべての操作または任意の操作が完了するまで待機するかどうかを指定できます。 この場合は、 の IAsyncResult プロパティをAsyncWaitHandle使用して、完了した操作を識別します。

state オブジェクトは、状態情報を操作に関連付けます。 たとえば、複数回呼び出 BeginReceive して複数の操作を開始する場合は、定義した個別の状態オブジェクトを使用して各操作を識別できます。

状態オブジェクトを使用して、プロセス スレッド間で情報を渡すこともできます。 スレッドが開始されたが、非同期シナリオでコールバックが別のスレッド上にある場合、状態オブジェクトはマーシャリングされ、イベントからの情報と共に返されます。

トランザクションで非同期呼び出し BeginReceive を使用しないでください。 トランザクション非同期操作を実行する場合は、 を呼び出 BeginPeekし、ピーク操作用に作成したイベント ハンドラー内にトランザクションと (同期) Receive メソッドを配置します。 イベント ハンドラーには、次の C# コードに示すように機能が含まれている場合があります。

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

次の表は、このメソッドがさまざまなワークグループ モードで使用できるかどうかを示しています。

ワークグループ モード 利用可能
ローカル コンピューター はい
ローカル コンピューターと直接形式の名前 はい
リモート コンピューター いいえ
リモート コンピューターと直接形式の名前 はい

こちらもご覧ください

適用対象

BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)

指定したタイムアウトがあり、指定したカーソルおよび状態オブジェクトを使用する非同期の受信操作を実行します。 状態オブジェクトは、操作の有効期間を通じて、関連付けられた情報を提供します。 このオーバーロードは、コールバックを通じて操作のイベント ハンドラー ID の通知を受信します。 この操作は、メッセージをキューで使用できるようになるか、タイムアウトが発生するまで完了しません。

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

メッセージを使用できるようになるまでの待機時間を示す TimeSpan

cursor
Cursor

メッセージ キュー内の特定の位置を維持する 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

非同期操作が完了したら、イベント ハンドラーで または BeginReceive をもう一度呼び出BeginPeekして、通知を受信し続けることができます。

IAsyncResultを返す BeginReceive は、メソッドが開始した非同期操作を識別します。 これは IAsyncResult 操作の有効期間中に使用できますが、通常は が呼び出されるまで EndReceive(IAsyncResult) 使用しません。 ただし、複数の非同期操作を開始する場合は、その値を IAsyncResult 配列に配置し、すべての操作または任意の操作が完了するまで待機するかどうかを指定できます。 この場合は、 の IAsyncResult プロパティをAsyncWaitHandle使用して、完了した操作を識別します。

state オブジェクトは、状態情報を操作に関連付けます。 たとえば、複数回を呼び出 BeginReceive して複数の操作を開始する場合は、定義した個別の状態オブジェクトを使用して各操作を識別できます。

state オブジェクトを使用して、プロセス スレッド間で情報を渡すこともできます。 スレッドが開始されていても、コールバックが非同期シナリオで別のスレッドにある場合、状態オブジェクトはマーシャリングされ、イベントからの情報と共に返されます。

トランザクションで非同期呼び出し BeginReceive を使用しないでください。 トランザクション非同期操作を実行する場合は、 を呼び出 BeginPeekし、ピーク操作用に作成したイベント ハンドラー内にトランザクションと (同期) Receive メソッドを配置します。 イベント ハンドラーには、次の C# コードに示すように機能が含まれている場合があります。

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

次の表は、このメソッドがさまざまなワークグループ モードで使用できるかどうかを示しています。

ワークグループ モード 利用可能
ローカル コンピューター はい
ローカル コンピューターと直接の形式名 はい
リモート コンピューター いいえ
リモート コンピューターと直接形式の名前 はい

こちらもご覧ください

適用対象

スレッド セーフ

メソッドはスレッド セーフではありません。