MessageQueue.BeginReceive Метод
Определение
Инициирует асинхронную операцию получения, указывая службе MSMQ на необходимость запуска операции получения сообщения и уведомления обработчика событий о завершении операции.Initiates an asynchronous receive operation by telling Message Queuing to begin receiving a message and notify the event handler when finished.
Перегрузки
BeginReceive() |
Инициирует асинхронную операцию получения без тайм-аута. Операция остается незавершенной, пока сообщение не станет доступным в очереди.Initiates an asynchronous receive operation that has no time-out. The operation is not complete until a message becomes available in the queue. |
BeginReceive(TimeSpan) |
Инициирует асинхронную операцию получения с указанным тайм-аутом. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.Initiates an asynchronous receive operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs. |
BeginReceive(TimeSpan, Object) |
Инициирует асинхронную операцию получения с указанным тайм-аутом и заданным объектом состояния, который предоставляет связанные данные в течение всего времени выполнения операции.Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.The operation is not complete until either a message becomes available in the queue or the time-out occurs. |
BeginReceive(TimeSpan, Object, AsyncCallback) |
Инициирует асинхронную операцию получения с указанным тайм-аутом и заданным объектом состояния, который предоставляет связанные данные в течение всего времени выполнения операции.Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. Посредством обратного вызова эта перегрузка получает уведомление об отличительных особенностях обработчика событий для операции.This overload receives notification, through a callback, of the identity of the event handler for the operation. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.The operation is not complete until either a message becomes available in the queue or the time-out occurs. |
BeginReceive(TimeSpan, Cursor, Object, AsyncCallback) |
Инициирует асинхронную операцию получения, которая имеет заданный тайм-аут и использует заданный курсор и заданный объект состояния.Initiates an asynchronous receive operation that has a specified time-out and uses a specified cursor and a specified state object. Объект состояния предоставляет связанные сведения в течение всего времени выполнения операции.The state object provides associated information throughout the lifetime of the operation. Посредством обратного вызова эта перегрузка получает уведомление об отличительных особенностях обработчика событий для операции.This overload receives notification, through a callback, of the identity of the event handler for the operation. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.The operation is not complete until either a message becomes available in the queue or the time-out occurs. |
BeginReceive()
Инициирует асинхронную операцию получения без тайм-аута. Операция остается незавершенной, пока сообщение не станет доступным в очереди.Initiates an asynchronous receive operation that has no time-out. The operation is not complete until a message becomes available in the queue.
public:
IAsyncResult ^ BeginReceive();
public IAsyncResult BeginReceive ();
member this.BeginReceive : unit -> IAsyncResult
Public Function BeginReceive () As IAsyncResult
Возвраты
Объект IAsyncResult, идентифицирующий размещенный асинхронный запрос.The IAsyncResult that identifies the posted asynchronous request.
Исключения
При обращении к методу службы очереди сообщений возникла ошибка.An error occurred when accessing a Message Queuing method.
Примеры
В следующем примере кода демонстрируется последовательное выполнение асинхронных запросов.The following code example chains asynchronous requests. Предполагается, что на локальном компьютере имеется очередь с именем «myQueue».It assumes there is a queue on the local computer called "myQueue". Функция Main
начинает асинхронную операцию, которая обрабатывается MyReceiveCompleted
подпрограммы.The Main
function begins the asynchronous operation that is handled by the MyReceiveCompleted
routine. MyReceiveCompleted
обрабатывает текущее сообщение и начинает новую асинхронную операцию получения.MyReceiveCompleted
processes the current message and begins a new asynchronous receive operation.
#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
В следующем примере кода асинхронные запросы поступают в очередь.The following code example queues asynchronous requests. Вызов BeginReceive использует AsyncWaitHandle в его возвращаемом значении.The call to BeginReceive uses the AsyncWaitHandle in its return value. Перед выходом подпрограмма Main
ожидает завершения всех асинхронных операций.The Main
routine waits for all asynchronous operations to be completed before exiting.
#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, когда сообщение было удалено из очереди.In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message has been removed from the queue.
ReceiveCompleted также создается, если сообщение уже существует в очереди.ReceiveCompleted is also raised if a message already exists in the queue.
Чтобы использовать BeginReceive, создайте обработчик событий, который обрабатывает результаты асинхронной операции и связывает его с делегатом события.To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive инициирует асинхронную операцию получения; MessageQueue уведомляется, вызывая событие ReceiveCompleted, когда сообщение поступает в очередь.BeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. После этого MessageQueue может получить доступ к сообщению, вызвав EndReceive(IAsyncResult).The MessageQueue can then access the message by calling EndReceive(IAsyncResult).
Метод BeginReceive возвращает значение немедленно, но асинхронная операция не завершается до вызова обработчика событий.The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.
Поскольку BeginReceive является асинхронным, его можно вызвать для получения сообщения из очереди, не блокируя текущий поток выполнения.Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. Чтобы синхронно получить сообщение, используйте метод Receive.To synchronously receive a message, use the Receive method.
После завершения асинхронной операции можно вызвать BeginPeek или BeginReceive в обработчике событий, чтобы получать уведомления.Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.
IAsyncResult, который BeginReceive возвращает, идентифицирует асинхронную операцию, запущенную методом.The IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. Этот IAsyncResult можно использовать в течение всего времени существования операции, хотя обычно он не используется, пока не будет вызвана EndReceive(IAsyncResult).You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. Однако при запуске нескольких асинхронных операций можно поместить их IAsyncResult значения в массив и указать, следует ли дожидаться завершения всех операций или любой операции.However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. В этом случае для задания завершенной операции используется свойство AsyncWaitHandle IAsyncResult.In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.
Если CanRead false
, вызывается событие завершения, но при вызове EndReceive(IAsyncResult)возникнет исключение.If CanRead is false
, the completion event is raised, but an exception will be thrown when calling EndReceive(IAsyncResult).
Не используйте асинхронный вызов BeginReceive с транзакциями.Do not use the asynchronous call BeginReceive with transactions. Если вы хотите выполнить транзакционную асинхронную операцию, вызовите BeginPeekи помещайте транзакцию и метод (синхронный) Receive в обработчике событий, созданном для операции просмотра.If you want to perform a transactional asynchronous operation, call BeginPeek, and put the transaction and the (synchronous) Receive method within the event handler you create for the peek operation. Обработчик событий может содержать функциональные возможности, как показано в следующем C# коде.Your event handler might contain functionality as shown in the following C# code.
myMessageQueue.BeginTransaction();
myMessageQueue.Receive();
myMessageQueue.CommitTransaction();
В следующей таблице показано, доступен ли этот метод в различных режимах рабочей группы.The following table shows whether this method is available in various Workgroup modes.
Режим рабочей группыWorkgroup mode | ДоступноAvailable |
---|---|
Локальный компьютерLocal computer | ДаYes |
Локальный компьютер и прямое имя форматаLocal computer and direct format name | ДаYes |
Удаленный компьютерRemote computer | НетNo |
Удаленный компьютер и прямое имя форматаRemote computer and direct format name | ДаYes |
Потокобезопасность
Метод не является потокобезопасным.The method is not thread safe.
Дополнительно
BeginReceive(TimeSpan)
Инициирует асинхронную операцию получения с указанным тайм-аутом. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.Initiates an asynchronous receive operation that has a specified time-out. The operation is not complete until either a message becomes available in the queue or the time-out occurs.
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, который показывает период времени ожидания доступности сообщения.A TimeSpan that indicates the interval of time to wait for a message to become available.
Возвраты
Объект IAsyncResult, идентифицирующий размещенный асинхронный запрос.The IAsyncResult that identifies the posted asynchronous request.
Исключения
Значение, заданное для параметра timeout
, недопустимо. Возможно, было введено отрицательное число.The value specified for the timeout
parameter is not valid, possibly because it represents a negative number.
При обращении к методу службы очереди сообщений возникла ошибка.An error occurred when accessing a Message Queuing method.
Примеры
В следующем примере кода создается асинхронная операция получения.The following code example creates an asynchronous receive operation. В примере кода создается обработчик событий, MyReceiveCompleted
и присоединяется к делегату обработчика событий ReceiveCompleted.The code example creates an event handler, MyReceiveCompleted
, and attaches it to the ReceiveCompleted event handler delegate. Пример кода отправляет сообщение в локальную очередь сообщений, а затем вызывает BeginReceive(TimeSpan), передавая значение времени ожидания в десять секунд.The code example sends a message to a local message queue, then calls BeginReceive(TimeSpan), passing in a time-out value of ten seconds. При возникновении события ReceiveCompleted обработчик событий получает сообщение и записывает текст сообщения на экран.When a ReceiveCompleted event is raised, the event handler receives the message and writes the message body to the screen.
#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, когда сообщение станет доступным в очереди или когда истечет указанный интервал времени.In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message becomes available in the queue or when the specified interval of time has expired.
ReceiveCompleted также создается, если сообщение уже существует в очереди.ReceiveCompleted is also raised if a message already exists in the queue.
Чтобы использовать BeginReceive, создайте обработчик событий, который обрабатывает результаты асинхронной операции и связывает его с делегатом события.To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive инициирует асинхронную операцию получения; MessageQueue уведомляется, вызывая событие ReceiveCompleted, когда сообщение поступает в очередь.BeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. Затем MessageQueue может получить доступ к сообщению, вызвав EndReceive(IAsyncResult) или извлекая результат с помощью ReceiveCompletedEventArgs.The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.
Метод BeginReceive возвращает значение немедленно, но асинхронная операция не завершается до вызова обработчика событий.The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.
Поскольку BeginReceive является асинхронным, его можно вызвать для получения сообщения из очереди, не блокируя текущий поток выполнения.Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. Чтобы синхронно получить сообщение, используйте метод Receive.To synchronously receive a message, use the Receive method.
После завершения асинхронной операции можно вызвать BeginPeek или BeginReceive в обработчике событий, чтобы получать уведомления.Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.
Если CanRead false
, вызывается событие завершения, но при вызове EndReceive(IAsyncResult)возникнет исключение.If CanRead is false
, the completion event is raised, but an exception will be thrown when calling EndReceive(IAsyncResult).
IAsyncResult, который BeginReceive возвращает, идентифицирует асинхронную операцию, запущенную методом.The IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. Этот IAsyncResult можно использовать в течение всего времени существования операции, хотя обычно он не используется, пока не будет вызвана EndReceive(IAsyncResult).You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. Однако при запуске нескольких асинхронных операций можно поместить их IAsyncResult значения в массив и указать, следует ли дожидаться завершения всех операций или любой операции.However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. В этом случае для задания завершенной операции используется свойство AsyncWaitHandle IAsyncResult.In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.
Эта перегрузка задает время ожидания. Если интервал, указанный параметром timeout
, истекает, этот компонент создает событие ReceiveCompleted.This overload specifies a time-out. If the interval specified by the timeout
parameter expires, this component raises the ReceiveCompleted event. Поскольку сообщение не существует, последующий вызов EndReceive(IAsyncResult) будет вызывать исключение.Because no message exists, a subsequent call to EndReceive(IAsyncResult) will throw an exception.
Не используйте асинхронный вызов BeginReceive с транзакциями.Do not use the asynchronous call BeginReceive with transactions. Если вы хотите выполнить транзакционную асинхронную операцию, вызовите BeginPeekи помещайте транзакцию и метод (синхронный) Receive в обработчике событий, созданном для операции просмотра.If you want to perform a transactional asynchronous operation, call BeginPeek, and put the transaction and the (synchronous) Receive method within the event handler you create for the peek operation. Обработчик событий может содержать функциональные возможности, как показано в следующем C# коде.Your event handler might contain functionality as shown in the following C# code.
myMessageQueue.BeginTransaction();
myMessageQueue.Receive();
myMessageQueue.CommitTransaction();
В следующей таблице показано, доступен ли этот метод в различных режимах рабочей группы.The following table shows whether this method is available in various Workgroup modes.
Режим рабочей группыWorkgroup mode | ДоступноAvailable |
---|---|
Локальный компьютерLocal computer | ДаYes |
Локальный компьютер и прямое имя форматаLocal computer and direct format name | ДаYes |
Удаленный компьютерRemote computer | НетNo |
Удаленный компьютер и прямое имя форматаRemote computer and direct format name | ДаYes |
Потокобезопасность
Метод не является потокобезопасным.The method is not thread safe.
Дополнительно
BeginReceive(TimeSpan, Object)
Инициирует асинхронную операцию получения с указанным тайм-аутом и заданным объектом состояния, который предоставляет связанные данные в течение всего времени выполнения операции.Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.The operation is not complete until either a message becomes available in the queue or the time-out occurs.
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, который показывает период времени ожидания доступности сообщения.A TimeSpan that indicates the interval of time to wait for a message to become available.
- stateObject
- Object
Задаваемый приложением объект состояния, который содержит сведения, связанные с асинхронной операцией.A state object, specified by the application, that contains information associated with the asynchronous operation.
Возвраты
Объект IAsyncResult, идентифицирующий размещенный асинхронный запрос.The IAsyncResult that identifies the posted asynchronous request.
Исключения
Значение, заданное для параметра timeout
, недопустимо.The value specified for the timeout
parameter is not valid.
При обращении к методу службы очереди сообщений возникла ошибка.An error occurred when accessing a Message Queuing method.
Примеры
В следующем примере кода создается асинхронная операция получения.The following code example creates an asynchronous receive operation. В примере кода создается обработчик событий, MyReceiveCompleted
и присоединяется к делегату обработчика событий ReceiveCompleted.The code example creates an event handler, MyReceiveCompleted
, and attaches it to the ReceiveCompleted event handler delegate. В примере кода сообщение отправляется в локальную очередь сообщений, затем вызывается BeginReceive(TimeSpan, Object), передача значения времени ожидания составляет десять секунд и уникальное целое число, идентифицирующее конкретное сообщение.The code example sends a message to a local message queue, then calls BeginReceive(TimeSpan, Object), passing in a time-out value of ten seconds and a unique integer that identifies that particular message. При возникновении события ReceiveCompleted обработчик событий получает сообщение и записывает на экран текст сообщения и идентификатор целочисленного сообщения.When a ReceiveCompleted event is raised, the event handler receives the message and writes the message body and the integer message identifier to the screen.
#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, когда сообщение станет доступным в очереди или когда истечет указанный интервал времени.In asynchronous processing, you use BeginReceive to raise the ReceiveCompleted event when a message becomes available in the queue or when the specified interval of time has expired.
ReceiveCompleted также создается, если сообщение уже существует в очереди.ReceiveCompleted is also raised if a message already exists in the queue.
Используйте эту перегрузку, чтобы связать сведения с операцией, которая будет сохранена в течение всего времени существования операции.Use this overload to associate information with the operation that will be preserved throughout the operation's lifetime. Обработчик событий может обнаружить эти сведения, просмотрев свойство AsyncState IAsyncResult, связанного с операцией.The event handler can detect this information by looking at the AsyncState property of the IAsyncResult that is associated with the operation.
Чтобы использовать BeginReceive, создайте обработчик событий, который обрабатывает результаты асинхронной операции и связывает его с делегатом события.To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive инициирует асинхронную операцию получения; MessageQueue уведомляется, вызывая событие ReceiveCompleted, когда сообщение поступает в очередь.BeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. Затем MessageQueue может получить доступ к сообщению, вызвав EndReceive(IAsyncResult) или извлекая результат с помощью ReceiveCompletedEventArgs.The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.
Метод BeginReceive возвращает значение немедленно, но асинхронная операция не завершается до вызова обработчика событий.The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.
Поскольку BeginReceive является асинхронным, его можно вызвать для получения сообщения из очереди, не блокируя текущий поток выполнения.Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. Чтобы синхронно получить сообщение, используйте метод Receive.To synchronously receive a message, use the Receive method.
После завершения асинхронной операции можно вызвать BeginPeek или BeginReceive в обработчике событий, чтобы получать уведомления.Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.
IAsyncResult, который BeginReceive возвращает, идентифицирует асинхронную операцию, запущенную методом.The IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. Этот IAsyncResult можно использовать в течение всего времени существования операции, хотя обычно он не используется, пока не будет вызвана EndReceive(IAsyncResult).You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. Однако при запуске нескольких асинхронных операций можно поместить их IAsyncResult значения в массив и указать, следует ли дожидаться завершения всех операций или любой операции.However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. В этом случае для задания завершенной операции используется свойство AsyncWaitHandle IAsyncResult.In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.
Эта перегрузка задает время ожидания и объект состояния.This overload specifies a time-out and a state object. Если интервал, указанный параметром timeout
, истекает, этот компонент создает событие ReceiveCompleted.If the interval specified by the timeout
parameter expires, this component raises the ReceiveCompleted event. Поскольку сообщение не существует, последующий вызов EndReceive(IAsyncResult) будет вызывать исключение.Because no message exists, a subsequent call to EndReceive(IAsyncResult) will throw an exception.
Объект состояния связывает сведения о состоянии с операцией.The state object associates state information with the operation. Например, если вы вызываете BeginReceive несколько раз для инициации нескольких операций, каждую операцию можно определить с помощью отдельного определяемого объекта State.For example, if you call BeginReceive multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.
Объект состояния также можно использовать для передачи сведений между потоками процесса.You can also use the state object to pass information across process threads. Если поток запущен, но обратный вызов находится в другом потоке в асинхронном сценарии, объект состояния маршалируется и передается обратно вместе со сведениями из события.If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.
Не используйте асинхронный вызов BeginReceive с транзакциями.Do not use the asynchronous call BeginReceive with transactions. Если вы хотите выполнить транзакционную асинхронную операцию, вызовите BeginPeekи помещайте транзакцию и метод (синхронный) Receive в обработчике событий, созданном для операции просмотра.If you want to perform a transactional asynchronous operation, call BeginPeek, and put the transaction and the (synchronous) Receive method within the event handler you create for the peek operation. Обработчик событий может содержать функциональные возможности, как показано в следующем C# коде.Your event handler might contain functionality as shown in the following C# code.
myMessageQueue.BeginTransaction();
myMessageQueue.Receive();
myMessageQueue.CommitTransaction();
В следующей таблице показано, доступен ли этот метод в различных режимах рабочей группы.The following table shows whether this method is available in various Workgroup modes.
Режим рабочей группыWorkgroup mode | ДоступноAvailable |
---|---|
Локальный компьютерLocal computer | ДаYes |
Локальный компьютер и прямое имя форматаLocal computer and direct format name | ДаYes |
Удаленный компьютерRemote computer | НетNo |
Удаленный компьютер и прямое имя форматаRemote computer and direct format name | ДаYes |
Потокобезопасность
Метод не является потокобезопасным.The method is not thread safe.
Дополнительно
BeginReceive(TimeSpan, Object, AsyncCallback)
Инициирует асинхронную операцию получения с указанным тайм-аутом и заданным объектом состояния, который предоставляет связанные данные в течение всего времени выполнения операции.Initiates an asynchronous receive operation that has a specified time-out and a specified state object, which provides associated information throughout the operation's lifetime. Посредством обратного вызова эта перегрузка получает уведомление об отличительных особенностях обработчика событий для операции.This overload receives notification, through a callback, of the identity of the event handler for the operation. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.The operation is not complete until either a message becomes available in the queue or the time-out occurs.
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, который показывает период времени ожидания доступности сообщения.A TimeSpan that indicates the interval of time to wait for a message to become available.
- stateObject
- Object
Задаваемый приложением объект состояния, который содержит сведения, связанные с асинхронной операцией.A state object, specified by the application, that contains information associated with the asynchronous operation.
- callback
- AsyncCallback
Объект AsyncCallback, принимающий уведомление о завершении асинхронной операции.The AsyncCallback that will receive the notification of the asynchronous operation completion.
Возвраты
Объект IAsyncResult, идентифицирующий размещенный асинхронный запрос.The IAsyncResult that identifies the posted asynchronous request.
Исключения
Значение, заданное для параметра timeout
, недопустимо.The value specified for the timeout
parameter is not valid.
При обращении к методу службы очереди сообщений возникла ошибка.An error occurred when accessing a Message Queuing method.
Примеры
В следующем примере кода создается асинхронная операция получения.The following code example creates an asynchronous receive operation. В примере кода сообщение отправляется в локальную очередь сообщений, затем вызывается BeginReceive(TimeSpan, Object, AsyncCallback), передача: время ожидания — десять секунд; уникальное целое число, идентифицирующее конкретное сообщение; и новый экземпляр AsyncCallback, который идентифицирует обработчик событий MyReceiveCompleted
.The code example sends a message to a local message queue, then calls BeginReceive(TimeSpan, Object, AsyncCallback), passing in: a time-out value of ten seconds; a unique integer that identifies that particular message; and a new instance of AsyncCallback that identifies the event handler, MyReceiveCompleted
. При возникновении события ReceiveCompleted обработчик событий получает сообщение и записывает на экран текст сообщения и идентификатор целочисленного сообщения.When a ReceiveCompleted event is raised, the event handler receives the message and writes the message body and the integer message identifier to the screen.
#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 не возникает.When you use this overload, the callback specified in the callback parameter is invoked directly when a message becomes available in the queue or when the specified interval of time has expired; the ReceiveCompleted event is not raised. Другие перегрузки BeginReceive используют этот компонент для вызова события ReceiveCompleted.The other overloads of BeginReceive rely on this component to raise the ReceiveCompleted event.
ReceiveCompleted также создается, если сообщение уже существует в очереди.ReceiveCompleted is also raised if a message already exists in the queue.
Чтобы использовать BeginReceive, создайте обработчик событий, который обрабатывает результаты асинхронной операции и связывает его с делегатом события.To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive инициирует асинхронную операцию получения; MessageQueue уведомляется, вызывая событие ReceiveCompleted, когда сообщение поступает в очередь.BeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. Затем MessageQueue может получить доступ к сообщению, вызвав EndReceive(IAsyncResult) или извлекая результат с помощью ReceiveCompletedEventArgs.The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.
Метод BeginReceive возвращает значение немедленно, но асинхронная операция не завершается до вызова обработчика событий.The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.
Поскольку BeginReceive является асинхронным, его можно вызвать для получения сообщения из очереди, не блокируя текущий поток выполнения.Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. Чтобы синхронно получить сообщение, используйте метод Receive.To synchronously receive a message, use the Receive method.
После завершения асинхронной операции можно вызвать BeginPeek или BeginReceive в обработчике событий, чтобы получать уведомления.Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.
IAsyncResult, который BeginReceive возвращает, идентифицирует асинхронную операцию, запущенную методом.The IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. Этот IAsyncResult можно использовать в течение всего времени существования операции, хотя обычно он не используется, пока не будет вызвана EndReceive(IAsyncResult).You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. Однако при запуске нескольких асинхронных операций можно поместить их IAsyncResult значения в массив и указать, следует ли дожидаться завершения всех операций или любой операции.However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. В этом случае для задания завершенной операции используется свойство AsyncWaitHandle IAsyncResult.In this case, you use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.
Объект состояния связывает сведения о состоянии с операцией.The state object associates state information with the operation. Например, если вы вызываете BeginReceive несколько раз для инициации нескольких операций, каждую операцию можно определить с помощью отдельного определяемого объекта State.For example, if you call BeginReceive multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.
Объект состояния также можно использовать для передачи сведений между потоками процесса.You can also use the state object to pass information across process threads. Если поток запущен, но обратный вызов находится в другом потоке в асинхронном сценарии, объект состояния маршалируется и передается обратно вместе со сведениями из события.If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.
Не используйте асинхронный вызов BeginReceive с транзакциями.Do not use the asynchronous call BeginReceive with transactions. Если вы хотите выполнить транзакционную асинхронную операцию, вызовите BeginPeekи помещайте транзакцию и метод (синхронный) Receive в обработчике событий, созданном для операции просмотра.If you want to perform a transactional asynchronous operation, call BeginPeek, and put the transaction and the (synchronous) Receive method within the event handler you create for the peek operation. Обработчик событий может содержать функциональные возможности, как показано в следующем C# коде.Your event handler might contain functionality as shown in the following C# code.
myMessageQueue.BeginTransaction();
myMessageQueue.Receive();
myMessageQueue.CommitTransaction();
В следующей таблице показано, доступен ли этот метод в различных режимах рабочей группы.The following table shows whether this method is available in various Workgroup modes.
Режим рабочей группыWorkgroup mode | ДоступноAvailable |
---|---|
Локальный компьютерLocal computer | ДаYes |
Локальный компьютер и прямое имя форматаLocal computer and direct format name | ДаYes |
Удаленный компьютерRemote computer | НетNo |
Удаленный компьютер и прямое имя форматаRemote computer and direct format name | ДаYes |
Потокобезопасность
Метод не является потокобезопасным.The method is not thread safe.
Дополнительно
BeginReceive(TimeSpan, Cursor, Object, AsyncCallback)
Инициирует асинхронную операцию получения, которая имеет заданный тайм-аут и использует заданный курсор и заданный объект состояния.Initiates an asynchronous receive operation that has a specified time-out and uses a specified cursor and a specified state object. Объект состояния предоставляет связанные сведения в течение всего времени выполнения операции.The state object provides associated information throughout the lifetime of the operation. Посредством обратного вызова эта перегрузка получает уведомление об отличительных особенностях обработчика событий для операции.This overload receives notification, through a callback, of the identity of the event handler for the operation. Операция остается незавершенной, пока сообщение не станет доступным в очереди или пока не истечет время ожидания.The operation is not complete until either a message becomes available in the queue or the time-out occurs.
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
Параметры
- timeout
- TimeSpan
Объект TimeSpan, который показывает период времени ожидания доступности сообщения.A TimeSpan that indicates the interval of time to wait for a message to become available.
- cursor
- Cursor
Объект Cursor, который сохраняет определенное положение в очереди сообщений.A Cursor that maintains a specific position in the message queue.
- state
- Object
Задаваемый приложением объект состояния, который содержит сведения, связанные с асинхронной операцией.A state object, specified by the application, that contains information associated with the asynchronous operation.
- callback
- AsyncCallback
Объект AsyncCallback, принимающий уведомление о завершении асинхронной операции.The AsyncCallback that receives the notification of the asynchronous operation completion.
Возвраты
Объект IAsyncResult, идентифицирующий размещенный асинхронный запрос.The IAsyncResult that identifies the posted asynchronous request.
Исключения
Параметр cursor
имеет значение null
.The cursor
parameter is null
.
Значение, заданное для параметра timeout
, недопустимо.The value specified for the timeout
parameter is not valid.
При обращении к методу службы очереди сообщений возникла ошибка.An error occurred when accessing a Message Queuing method.
Комментарии
При использовании этой перегрузки функция обратного вызова, указанная в параметре обратного вызова, вызывается непосредственно в том случае, когда сообщение становится доступным в очереди или по истечении заданного интервала времени. событие ReceiveCompleted не возникает.When you use this overload, the callback specified in the callback parameter is invoked directly when a message becomes available in the queue or when the specified interval of time has expired; the ReceiveCompleted event is not raised. Другие перегрузки BeginReceive используют этот компонент для вызова события ReceiveCompleted.The other overloads of BeginReceive rely on this component to raise the ReceiveCompleted event.
ReceiveCompleted также создается, если сообщение уже существует в очереди.ReceiveCompleted is also raised if a message already exists in the queue.
Чтобы использовать BeginReceive, создайте обработчик событий, который обрабатывает результаты асинхронной операции и связывает его с делегатом события.To use BeginReceive, create an event handler that processes the results of the asynchronous operation and associate it with your event delegate. BeginReceive инициирует асинхронную операцию получения; MessageQueue уведомляется, вызывая событие ReceiveCompleted, когда сообщение поступает в очередь.BeginReceive initiates an asynchronous receive operation; the MessageQueue is notified, through the raising of the ReceiveCompleted event, when a message arrives in the queue. Затем MessageQueue может получить доступ к сообщению, вызвав EndReceive(IAsyncResult) или извлекая результат с помощью ReceiveCompletedEventArgs.The MessageQueue can then access the message by calling EndReceive(IAsyncResult) or retrieving the result using the ReceiveCompletedEventArgs.
Метод BeginReceive возвращает значение немедленно, но асинхронная операция не завершается до вызова обработчика событий.The BeginReceive method returns immediately, but the asynchronous operation is not completed until the event handler is called.
Поскольку BeginReceive является асинхронным, его можно вызвать для получения сообщения из очереди, не блокируя текущий поток выполнения.Because BeginReceive is asynchronous, you can call it to receive a message from the queue without blocking the current thread of execution. Чтобы синхронно получить сообщение, используйте метод Receive.To synchronously receive a message, use the Receive method.
После завершения асинхронной операции можно вызвать BeginPeek или BeginReceive в обработчике событий, чтобы получать уведомления.Once an asynchronous operation completes, you can call BeginPeek or BeginReceive again in the event handler to keep receiving notifications.
IAsyncResult, который BeginReceive возвращает, идентифицирует асинхронную операцию, запущенную методом.The IAsyncResult that BeginReceive returns identifies the asynchronous operation that the method started. Этот IAsyncResult можно использовать в течение всего времени существования операции, хотя обычно он не используется, пока не будет вызвана EndReceive(IAsyncResult).You can use this IAsyncResult throughout the lifetime of the operation, although you generally do not use it until EndReceive(IAsyncResult) is called. Однако при запуске нескольких асинхронных операций можно поместить их IAsyncResult значения в массив и указать, следует ли дожидаться завершения всех операций или любой операции.However, if you start several asynchronous operations, you can place their IAsyncResult values in an array and specify whether to wait for all operations or any operation to complete. В этом случае используйте свойство AsyncWaitHandle IAsyncResult, чтобы указать завершенную операцию.In this case, use the AsyncWaitHandle property of the IAsyncResult to identify the completed operation.
Объект состояния связывает сведения о состоянии с операцией.The state object associates state information with the operation. Например, если вы вызываете BeginReceive несколько раз для инициации нескольких операций, каждую операцию можно определить с помощью отдельного определяемого объекта State.For example, if you call BeginReceive multiple times to initiate multiple operations, you can identify each operation through a separate state object that you define.
Объект состояния также можно использовать для передачи сведений между потоками процесса.You can also use the state object to pass information across process threads. Если поток запущен, но обратный вызов находится в другом потоке в асинхронном сценарии, объект состояния маршалируется и передается обратно вместе со сведениями из события.If a thread is started but the callback is on a different thread in an asynchronous scenario, the state object is marshaled and passed back along with information from the event.
Не используйте асинхронный вызов BeginReceive с транзакциями.Do not use the asynchronous call BeginReceive with transactions. Если вы хотите выполнить транзакционную асинхронную операцию, вызовите BeginPeekи помещайте транзакцию и метод (синхронный) Receive в обработчике событий, созданном для операции просмотра.If you want to perform a transactional asynchronous operation, call BeginPeek, and put the transaction and the (synchronous) Receive method within the event handler you create for the peek operation. Обработчик событий может содержать функциональные возможности, как показано в следующем C# коде.Your event handler might contain functionality as shown in the following C# code.
myMessageQueue.BeginTransaction();
myMessageQueue.Receive();
myMessageQueue.CommitTransaction();
В следующей таблице показано, доступен ли этот метод в различных режимах рабочей группы.The following table shows whether this method is available in various Workgroup modes.
Режим рабочей группыWorkgroup mode | ДоступноAvailable |
---|---|
Локальный компьютерLocal computer | ДаYes |
Локальный компьютер и прямое имя форматаLocal computer and direct format name | ДаYes |
Удаленный компьютерRemote computer | НетNo |
Удаленный компьютер и прямое имя форматаRemote computer and direct format name | ДаYes |
Потокобезопасность
Метод не является потокобезопасным.The method is not thread safe.