rhatwar007
rhatwar007

Reputation: 343

Throw InvalidCastException while Sending Serialized Data to MSMQ

I am try to send serialized data to MSMQ but getting "System.InvalidCastException: Specified cast is not valid." error. I Put my Send Method and Log follow. Please suggest me some solution over this error.

    // Here MyMessage is my class which contain some
    // stuff which I want to pass to MSMQ.
    public void Send(MyMessage myMessage)
    {
        XmlSerializer ser = new XmlSerializer(typeof(MyMessage));
        StringBuilder sb = new StringBuilder();

        using (StringWriter writer = new StringWriter())
        {
            ser.Serialize(writer, myMessage);

            Debug.WriteLine(writer.ToString());
        }
      Message _myMessage = new Message(myMessage, new BinaryMessageFormatter());
      //_messageQueue is object of MSMQMessage
      _messageQueue.Send(_myMessage);
     }

Log :

System.InvalidCastException: Specified cast is not valid." at MyClassName.Send(MyMessage myMessage)

Suggestion : I think this error is occurs due to "typeof" but I am not sure on that front.

Upvotes: 2

Views: 1209

Answers (2)

tolrahC
tolrahC

Reputation: 135

I know I'm late, but I had the same issue today and solved it. Since it's one of the first link to popup in Google, I will share my solution.

In your code you are using a global message queue variable. The Send method is not thread safe, so if you have multiple thread that try to send a message using the same object you may have this kind of error.

One solution is to use the lock function

// Here MyMessage is my class which contain some
// stuff which I want to pass to MSMQ.
public void Send(MyMessage myMessage)
{
    XmlSerializer ser = new XmlSerializer(typeof(MyMessage));
    StringBuilder sb = new StringBuilder();

    using (StringWriter writer = new StringWriter())
    {
        ser.Serialize(writer, myMessage);

        Debug.WriteLine(writer.ToString());
    }
    Message _myMessage = new Message(myMessage, new BinaryMessageFormatter());
    //_messageQueue is object of MSMQMessage
    lock(_objlck)
    {
        _messageQueue.Send(_myMessage);
    }
 }

One other option is to have a new instance of MessageQueue in each thread.

That worked for me.

Upvotes: 8

Vazgen Torosyan
Vazgen Torosyan

Reputation: 1295

set [Serializable] prpoerty to AuditMessage.

Upvotes: 1

Related Questions