开发者

Mutex needed in MSMQ?

I'm browsing source codes from two applications sharin开发者_如何转开发g one queue using MSMQ. The first application has a thread that writes into the queue while the second application has another thread that reads from the queue. Ordinarily, if you're implementing your own queue, the applications would need a mutex when accessing the queue, right? However, I could not find any mutex/critical section in the source codes of these applications. Did I just miss something? Or does MSMQ not need any mutex since it is handled internally, is there such thing?


The MSMQ documentation states that:

Only the following methods are thread safe: BeginPeek, BeginReceive, EndPeek(IAsyncResult), EndReceive(IAsyncResult), GetAllMessages, Peek, and Receive.

MSMQ.Send() is not inherently thread-safe.

Send is thread safe, as long as you always send a Message object and never use send a .NET object directly. Using the Message object, BTW, is always a good idea - since it lets you add label, timeouts, recoverable option and all this stuff that make your MSMQ solution a real enterprise solution.

class Program
{
    static MessageQueue outQueue;
    static void Main(string[] args)
    {
        outQueue = new MessageQueue(@".\private$\mtQueue"); 

        for (int i = 0; i < 100; i++)
        {
            Thread thr = new Thread(new ThreadStart(MyThreadProc));

            thr.Start();
        }
    } 

    static void MyThreadProc()
    {
        Message msg = new Message();
        for (int i = 0; i < 100; i++)
        {
            msg.Label = string.Format("{0} : {1}",
                                     Thread.CurrentThread.ManagedThreadId,
                                      i);
            outQueue.Send(msg);
        }
    }
}

From: Is Send() thread safe?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜