문제

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?

도움이 되었습니까?

해결책

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?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top