MessageQueue.EndPeek(IAsyncResult) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Завершает указанную асинхронную операцию просмотра.
public:
System::Messaging::Message ^ EndPeek(IAsyncResult ^ asyncResult);
public System.Messaging.Message EndPeek(IAsyncResult asyncResult);
member this.EndPeek : IAsyncResult -> System.Messaging.Message
Public Function EndPeek (asyncResult As IAsyncResult) As Message
Параметры
- asyncResult
- IAsyncResult
Объект IAsyncResult , определяющий асинхронную операцию просмотра для завершения и из которой требуется получить конечный результат.
Возвращаемое значение
Связанная Message с завершенной асинхронной операцией.
Исключения
Параметр asyncResult имеет значение null.
Недопустимый asyncResult синтаксис параметра.
Произошла ошибка при доступе к методу очереди сообщений.
Примеры
Следующий пример кода создает обработчик событий с именем MyPeekCompleted, присоединяет его к PeekCompleted делегату обработчика событий и вызывает BeginPeek асинхронную операцию просмотра в очереди, расположенной по пути .\myQueue.
PeekCompleted При возникновении события пример выводит сообщение и записывает его текст на экран. Затем этот пример снова вызывается BeginPeek для запуска новой асинхронной операции просмотра.
#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
Комментарии
PeekCompleted Когда событие возникает, завершит операцию, EndPeek(IAsyncResult) инициированную вызовомBeginPeek. Для этого EndPeek(IAsyncResult) проглядывает сообщение.
BeginPeek может указать время ожидания, которое приводит к возникновению события, если время ожидания возникает PeekCompleted до появления сообщения в очереди. Если время ожидания происходит без сообщения, поступающего в очередь, последующий вызов EndPeek(IAsyncResult) вызывает исключение.
EndPeek(IAsyncResult) используется для чтения сообщения, которое привело PeekCompleted к возникновению события.
Если вы хотите продолжать асинхронно просматривать сообщения, вы можете снова вызвать BeginPeek после вызова EndPeek(IAsyncResult).
В следующей таблице показано, доступен ли этот метод в различных режимах рабочей группы.
| Режим рабочей группы | В наличии |
|---|---|
| Локальный компьютер | Yes |
| Имя локального компьютера и прямого формата | Yes |
| Удаленный компьютер | Нет |
| Имя удаленного компьютера и прямого формата | Yes |