Share data through MSMQ

来源:互联网 发布:淘宝虚拟店铺入驻 编辑:程序博客网 时间:2024/04/29 06:53

firstly. you have to install MSMQ in your computer. Open your add/remove component in your control panel. Select Application Server/Message Queuing, then click OK to finish installing.

In Computer panel you can find Message Queuing node. It demostrates that you have successfully installed the MSMQ. Now let's create a MSMQ for our demo. Right click the Private Queues and select new-->private Queue and named it as MyQueue.

 

secondly, Create two Windows application for the demo. It will realize the Sender and Receiver of the MSMQ.

In the Sender application, you will add a MessageQueue component to the project. It named messageQueue1. Configure it property as follows. The most important two property.
one is Path = ./private$/MyQueue  (. represents the local machine)
the other is Formatter = BinaryMessageFormatter (serilized Formatter)

Another application need the same configure, thus they point to the same MSMQ.

thirdly, write some code about send and receiver.
Sender Application:

private void Sender_Click(object sender, EventArgs e)
{
    System.Collections.ArrayList al = new System.Collections.ArrayList();
    al.Add("Henry");
    al.Add("Tom");
    al.Add("Jenny");
    this.messageQueue1.Send(al, "My first MSMQ");
}

Receiver Application:
private void Receiver_Click(object sender, EventArgs e)
{
    messageQueue1.BeginReceive();
}

private void messageQueue1_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
{
    System.Messaging.Message msg = null;
    msg = messageQueue1.EndReceive(e.AsyncResult);
    System.Collections.ArrayList al = (System.Collections.ArrayList)msg.Body;
    string str = "";
    for (int i = 0; i < al.Count; i++)
    {
        str += al[i].ToString() + "/n";
    }
    MessageBox.Show(str);
}

ok, you can test it. enjoy MSMQ. very easy. 

原创粉丝点击