PeekCompletedEventArgs Класс

Определение

Предоставляет данные для события PeekCompleted. Когда асинхронная операция считывания вызывает обработчик событий, экземпляр этого класса передается в обработчик.

public ref class PeekCompletedEventArgs : EventArgs
public class PeekCompletedEventArgs : EventArgs
type PeekCompletedEventArgs = class
    inherit EventArgs
Public Class PeekCompletedEventArgs
Inherits EventArgs
Наследование
PeekCompletedEventArgs

Примеры

В следующем примере кода создается обработчик событий для PeekCompleted события и связывается с делегатом события с помощью PeekCompletedEventHandler. Обработчик MyPeekCompletedсобытий просматривает сообщение и записывает его метку на экран.

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

using namespace System;
using namespace System::Messaging;

// This example performs asynchronous peek operation
// processing.
//*************************************************
ref class MyNewQueue
{
public:

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

      // End the asynchronous peek operation.
      Message^ m = mq->EndPeek( asyncResult->AsyncResult );

      // Display message information on the screen.
      Console::WriteLine( "Message: {0}", static_cast<String^>(m->Body) );

      // Restart the asynchronous peek operation.
      mq->BeginPeek();
      return;
   }
};

// Provides an entry point into the application.
//         
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 PeekCompleted event.
   myQueue->PeekCompleted += gcnew PeekCompletedEventHandler( MyNewQueue::MyPeekCompleted );

   // Begin the asynchronous peek operation.
   myQueue->BeginPeek();

   // Do other work on the current thread.
   return 0;
}
using System;
using System.Messaging;

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 peek 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 PeekCompleted event.
            myQueue.PeekCompleted += new
                PeekCompletedEventHandler(MyPeekCompleted);

            // Begin the asynchronous peek operation.
            myQueue.BeginPeek();

            // Do other work on the current thread.

            return;
        }

        //**************************************************
        // Provides an event handler for the PeekCompleted
        // event.
        //**************************************************

        private static void MyPeekCompleted(Object source,
            PeekCompletedEventArgs asyncResult)
        {
            // Connect to the queue.
            MessageQueue mq = (MessageQueue)source;

            // End the asynchronous peek operation.
            Message m = mq.EndPeek(asyncResult.AsyncResult);

            // Display message information on the screen.
            Console.WriteLine("Message: " + (string)m.Body);

            // Restart the asynchronous peek operation.
            mq.BeginPeek();

            return;
        }
    }
}
Imports System.Messaging





' Provides a container class for the example.
Public Class MyNewQueue



        ' Provides an entry point into the application.
        '		 
        ' This example performs asynchronous peek 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 PeekCompleted event.
            AddHandler myQueue.PeekCompleted, AddressOf _
                MyPeekCompleted

            ' Begin the asynchronous peek operation.
            myQueue.BeginPeek()

            ' Do other work on the current thread.
            Return
        End Sub


        '**************************************************
        ' Provides an event handler for the PeekCompleted
        ' event.
        '**************************************************

        Private Shared Sub MyPeekCompleted(ByVal [source] As _
            [Object], ByVal asyncResult As PeekCompletedEventArgs)

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

            ' End the asynchronous peek operation.
            Dim m As Message = mq.EndPeek(asyncResult.AsyncResult)

            ' Display message information on the screen.
            Console.WriteLine(("Message: " + CStr(m.Body)))

            ' Restart the asynchronous peek operation.
            mq.BeginPeek()

            Return

        End Sub

End Class

Комментарии

При использовании уведомления о событиях для асинхронного просмотра (чтения без удаления) сообщений из очереди необходимо создать метод, обрабатывающий обработку сообщений. Код должен вызвать , BeginPeek чтобы начать асинхронную обработку. При просмотре сообщения приложение получает уведомление через PeekCompleted событие . Экземпляр PeekCompletedEventArgs передается в делегат события, который вызывает обработчик событий. Данные, связанные с событием PeekCompleted , содержатся в параметре делегата AsyncResult .

Существует два способа предоставления уведомлений о завершении события: уведомление о событии и обратные вызовы. PeekCompletedEventArgs используется только с уведомлением о событии. Сведения о сравнении обратных вызовов и уведомлений о событиях см. в разделе "События и обратные вызовы" на сайте MSDN.

PeekCompletedEventArgs предоставляет доступ к сообщению, которое инициировало окончание операции асинхронного просмотра, через Message элемент . Это альтернативный доступ к сообщению и ведет себя практически так же, как вызов MessageQueue.EndPeek.

Свойства

AsyncResult

Получает или задает результат запрошенной асинхронной операции.

Message

Получает сообщение, связанное с данной асинхронной операцией считывания.

Методы

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

См. также раздел