I only want to receive my message in a async method! and its freezing my UI
public async void ProcessMessages()
{
MessageQueue MyMessageQueue = n
As Stephen writes, async doesn't run your code in a thread. Fortunately, you can use TaskFactory.FromAsync with MessageQueue.BeginReceive/MessageQueue.EndReceive to receive messages asynchronously:
private async Task MyAsyncReceive()
{
MessageQueue queue=new MessageQueue();
...
var message=await Task.Factory.FromAsync(
queue.BeginReceive(),
queue.EndReceive);
return message;
}
You should note though that there ISN'T a version of BeginReceive that uses a Transaction. From BeginReceive's docs:
Do not use the asynchronous call BeginReceive with transactions. 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.
This makes sense as there is no guarantee how long you have to wait for a response or which thread will eventually handle the completed call.
To use transactions you would write something like this:
private async Task MyAsyncReceive()
{
var queue=new MessageQueue();
var message=await Task.Factory.FromAsync(queue.BeginPeek(),queue.EndPeek);
using (var tx = new MessageQueueTransaction())
{
tx.Begin();
//Someone may have taken the last message, don't wait forever
//Use a smaller timeout if the queue is local
message=queue.Receive(TimeSpan.FromSeconds(1), tx);
//Process the results inside a transaction
tx.Commit();
}
return message;
}
UPDATE
As Rob pointed out, the original code used the message
returned from Peek
, which may have changed between Peek
and Receive
. In this case the second message will be lost.
There's still a chance of blocking though, if another client reads the last message in the queue. To prevent this, Receive
should have a small timeout.