消息队列
首先,测试了几个异常情况下的案例:
1:接收方断网;
2:发送方断网;
3:发送方关机;
发现,1和2在默认情况下就能满足,3需要对消息的Recoverable设置为true;
发送方代码如下:
public System.Messaging.MessageQueue helpRequestQueue=
new System.Messaging.MessageQueue();
private void sendMessage_Click(object sender, EventArgs e)
{
try
{
MessageQ m1 = new MessageQ(helpRequestQueue, "mmmm", false);
Thread t1 = new Thread(m1.SendMq);
t1.Start();
MessageQ m2 = new MessageQ(helpRequestQueue, "nnnn", true);
Thread t2 = new Thread(m2.SendMq);
t2.Start();
}
catch (Exception e3)
{
MessageBox.Show(e3.StackTrace);
//throw;
}
}
[Serializable]
public class Book
{
public string name;
public int bookId;
public Book()
{
}
public Book(string name, int bookId)
{
this.name = name;
this.bookId = bookId;
}
}
class MessageQ
{
string name;
System.Messaging.Message theMessage = new System.Messaging.Message("");
bool be = false;
System.Messaging.MessageQueue mq;
public MessageQ(System.Messaging.MessageQueue mq,string name, bool be)
{
this.mq = mq;
this.name = name;
this.be = be;
}
public void SendMq()
{
theMessage.Recoverable = true;
for (int i = 0; i < 10; i++)
{
Book b = new Book(name, 21);
theMessage.Body = b;
theMessage.Formatter = new XmlMessageFormatter(new Type[] { typeof(Book) });
mq.Send(theMessage);
Debug.Print("" + i);
if (be)
{
Thread.Sleep(1001);
}
else
{
Thread.Sleep(1002);
}
}
}
}
接收方代码如下:
int i = 0;
private void mq_ReceiveCompleted(object sender, System.Messaging.ReceiveCompletedEventArgs e)
{
i++;
System.Messaging.Message m = mq.EndReceive(e.AsyncResult);
//m.Formatter = new System.Messaging.XmlMessageFormatter(
// new string[] { "System.String,mscorlib" });
m.Formatter = new XmlMessageFormatter(new Type[] { typeof(Book) });
//Console.WriteLine("Message: " + (string)m.Body);
Book book = (Book)m.Body;
Debug.Print(book.name + i);
mq.BeginReceive();
}
public class Book
{
public string name;
public int bookId;
public Book()
{
}
public Book(string name, int bookId)
{
this.name = name;
this.bookId = bookId;
}
}
消息队列示例程序
最新推荐文章于 2024-02-05 16:58:01 发布