开发者

MSMQ receive timeouts from .NET

开发者 https://www.devze.com 2023-02-28 17:49 出处:网络
I want to be able to read and process messages from MSMQ. The queues are transactional. I\'m currently using this code:

I want to be able to read and process messages from MSMQ. The queues are transactional. I'm currently using this code:

while (true)
{
    using (var txn = new MessageQueueTransaction())
    {
        txn.Begin();

        try
        {
            var message = queue.Receive(txn);
            Dispatch(message);

            txn.Commit();
        }
        catch (MessageQueueException ex)
        {
            txn.Abort();
        }
    }
}

Where queue is a System.Messaging.MessageQueue.

I'd like to make开发者_如何学Python the loop use while (!cancelled), which would mean calling the queue.Receive that overload that accepts a timeout. However, the code throws when the timeout is reached, and throwing so many exceptions can't be a good thing. Is there a TryRecieve, similar to Monitor.TryEnter? Peek seems to be the closest, but it also throws when the timeout is reached.

If I want high throughput reading from a queue and cancellation support, what's the best way to read from the queue?


Use MessageQueue.BeginPeek() instead. The event handler you write for the PeekCompleted event will run as soon as a message is available. You can call Receive() and be sure you'll get a message without a timeout. There's a good example in the MSDN Library article.


Not a direct answer, but I would use the net.msmq protocol in WCF to do my messageQ handling. Its a neat simple approach and can cater for all the scenarios you have mentioned here.

0

精彩评论

暂无评论...
验证码 换一张
取 消