S
S
Slavka2016-10-04 21:53:17
C++ / C#
Slavka, 2016-10-04 21:53:17

Serialization crashes while running in a parallel thread?

private void receiving()
        {
            while (isRecieving)
            {
              try { 
                byte[] bytes = new byte[4];
                _socket.Receive(bytes);
                int sizeForBuffer = BitConverter.ToInt32(bytes, 0);
                bytes = new byte[sizeForBuffer];

                while (sizeForBuffer != _socket.Receive(bytes)) ;
                BinaryFormatter bf = new BinaryFormatter();
                using (MemoryStream ms = new MemoryStream(bytes))
                {
                    Message message = (Message)bf.Deserialize(ms);
                    _history.Add(message);
                }
            }
           catch(System.Runtime.Serialization.SerializationException e)
                {

                }     

            }

        }

such code works in a separate task (it just accepts data allegedly from the server) and if you remove the try / catch block, you will get an exception with the following text " Binary stream "0" does not contain a valid binary header BinaryHeader. Possible reasons: invalid stream or change of the object version between serialization and deserialization." Nowhere can I find a reason to explain this, if you catch the exception everything works fine. I'm new to multi-threaded programming.
================================================= =========================================
PS Error in receiving bytes

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question