具有不同消息类型的消息队列

Jul*_*old 10 c# msmq

我正在调查Microsoft Message Queues以进行进程间跨网络消息传递.但是,当我收到一个消息,我不知道先验什么对象我得到的类型,所以代码

queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(Wibble) });
Run Code Online (Sandbox Code Playgroud)

收到消息之前无法应用,因为我不知道它是否是一个Wibble.那么我如何收到不同的消息类型?

Dam*_*ver 12

您已经在使用构造函数重载,因为XmlMessageFormatter它接受了一系列类型.因此,只需将您期望接收的所有类型添加到该数组中,而不仅仅是一种类型.

queue.Formatter = new XmlMessageFormatter(new Type[] {
    typeof(Wibble),
    typeof(Fleem),
    typeof(Boo)
});
Run Code Online (Sandbox Code Playgroud)

来自TargetTypes:

消息体中序列化的实例必须符合类型数组中表示的其中一个模式.当您使用Receive方法读取消息时,该方法将创建与所标识的模式对应的类型的对象,并将消息正文读入其中.

(重点补充)


tal*_*eth 3

您可能会考虑不在 MSMQ 消息中存储对象,而是在可以的情况下放置对其持久位置的引用。MSMQ 的消息队列空间有限,因此较小的消息是最好的。

如果您做不到这一点,您可以使用您喜欢的任何序列化程序将对象直接序列化到消息 BodyStream。然后也存储类型名称,可能最好存储在消息标签中。

与此非常相似的东西(在这里划掉它,这台计算机上没有 IDE)将其放入,以及退出时的类似操作:

public void FormatObject(object toFormat, Message message)
{
    var serializer = new XmlSerializer(toFormat.GetType());
    var stream = new MemoryStream();
    serializer.Serialize(toFormat, stream);

    //don't dispose the stream
    message.BodyStream = stream;
    message.Label = toFormat.GetType().AssemblyQualifiedName;
}
Run Code Online (Sandbox Code Playgroud)