ReceiveCompletedEventArgs Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Предоставляет данные для ReceiveCompleted события. Когда асинхронная операция получения вызывает обработчик событий, экземпляр этого класса передается обработчику.
public ref class ReceiveCompletedEventArgs : EventArgs
public class ReceiveCompletedEventArgs : EventArgs
type ReceiveCompletedEventArgs = class
inherit EventArgs
Public Class ReceiveCompletedEventArgs
Inherits EventArgs
- Наследование
Примеры
В следующем примере кода создается обработчик событий для ReceiveCompleted события и связывает его с делегатом события с помощью .ReceiveCompletedEventHandler Обработчик событий получает MyReceiveCompletedсообщение из очереди и записывает его текст на экран.
#using <system.dll>
#using <system.messaging.dll>
using namespace System;
using namespace System::Messaging;
ref class MyNewQueue
{
public:
//*************************************************
// Provides an event handler for the ReceiveCompleted
// event.
//*************************************************
static void MyReceiveCompleted( Object^ source, ReceiveCompletedEventArgs^ asyncResult )
{
// Connect to the queue.
MessageQueue^ mq = dynamic_cast<MessageQueue^>(source);
// End the asynchronous Receive operation.
Message^ m = mq->EndReceive( asyncResult->AsyncResult );
// Display message information on the screen.
Console::WriteLine( "Message: {0}", m->Body );
// Restart the asynchronous Receive operation.
mq->BeginReceive();
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();
// 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 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();
// Do other work on the current thread.
return;
}
//**************************************************
// Provides an event handler for the ReceiveCompleted
// event.
//**************************************************
private static void MyReceiveCompleted(Object source,
ReceiveCompletedEventArgs asyncResult)
{
// Connect to the queue.
MessageQueue mq = (MessageQueue)source;
// End the asynchronous Receive operation.
Message m = mq.EndReceive(asyncResult.AsyncResult);
// Display message information on the screen.
Console.WriteLine("Message: " + (string)m.Body);
// Restart the asynchronous Receive operation.
mq.BeginReceive();
return;
}
}
}
Imports System.Messaging
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
' Begin the asynchronous receive operation.
myQueue.BeginReceive()
' 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)
' Connect to the queue.
Dim mq As MessageQueue = CType([source], MessageQueue)
' End the asynchronous Receive operation.
Dim m As Message = mq.EndReceive(asyncResult.AsyncResult)
' Display message information on the screen.
Console.WriteLine(("Message: " + CStr(m.Body)))
' Restart the asynchronous Receive operation.
mq.BeginReceive()
Return
End Sub
End Class
Комментарии
При использовании уведомления о событии для асинхронного получения сообщений из очереди необходимо создать метод, который обрабатывает обработку сообщений. Код должен вызвать BeginReceive асинхронную обработку. При получении сообщения приложение уведомляется через ReceiveCompleted событие. Экземпляр ReceiveCompletedEventArgs передается в делегат события, вызывающий обработчик событий. Данные, связанные с ReceiveCompleted событием, содержатся в параметре делегата AsyncResult .
Существует два способа предоставления уведомления о завершении события: уведомления о событиях и обратных вызовах. ReceiveCompletedEventArgs используется только с уведомлением о событии. Сведения о сравнении обратных вызовов и уведомлений о событиях см. в разделе "События и обратные вызовы" в MSDN.
ReceiveCompletedEventArgs предоставляет доступ к сообщению, инициируемого завершением асинхронной операции получения через Message член. Это альтернативный доступ к сообщению и ведет себя так же, как вызов MessageQueue.EndReceive.
Свойства
| Имя | Описание |
|---|---|
| AsyncResult |
Возвращает или задает результат запрошенной асинхронной операции. |
| Message |
Возвращает сообщение, связанное с асинхронной операцией получения. |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |