views:

49

answers:

1

I'm browsing source codes from two applications sharing 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?

A: 

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?

Mitch Wheat
I'm not sure if I understood your last statement. Create a separate instance of the queue on each thread and let MSMQ handle messages from different threads - do I need to use mutex for this?
jasonline
Yes, if I create a separate instance of the MSMQ object on each thread, then I don't need to use a mutex right?
jasonline
actually, after more digging please see my updated answer...
Mitch Wheat
I see then, thanks for the additional information.
jasonline
if it solves your problem, feel free to vote up! ;)
Mitch Wheat
How come I dont' see your answer "Create a separate instance of the queue on each thread and let MSMQ handle messages from different threads" anymore.. This was actually the one that made it correct.
jasonline