5

I have problems with Windows 8 UI application. I'm using client-server communication and client needs to check new messages all time. So I use such code, where _socket is a StreamSoket:

    private async static void MessageReceiver()
    {
        var dataReader = new DataReader(_socket.InputStream);
        dataReader.InputStreamOptions = InputStreamOptions.Partial;

        var stringHeader = await dataReader.LoadAsync(4);
        if (stringHeader != 0)
        {
            var bytes = new byte[4];
            dataReader.ReadBytes(bytes);
            var length = BitConverter.ToInt32(bytes, 0);

            var count = await dataReader.LoadAsync((uint) length);

            var result = dataReader.ReadString(count);

            ParseRequest(result);
        }

        dataReader.DetachStream();


        MessageReceiver();
    }

But in the second LoadAsync, when I try to read the string, I have ObjectDisposedException. Can you help me with it? I have no idea, why such exception is thrown. I've also tried to use DataReader.InputStream.ReadAsync(), but I also had such problem.

Youngjae
  • 24,352
  • 18
  • 113
  • 198
Dmitriy Bondarchuk
  • 111
  • 1
  • 2
  • 9

2 Answers2

2

I know this is an old post but since I was having the same problem and figured it out I thought I would post the solution for anyone else that stumbles across this. Although I won't claim to know exactly what the cause of this problem is, since I'm primarily a C++ guy, the solution was fairly simple.

The way I fixed it was by declaring the DataReader as a class member, thereby extending it's scope

_socket= new StreamSocket();
_socket.Control.KeepAlive = true;
_socket.Control.NoDelay = true;
_socketReader = new DataReader(_socket.InputStream);
_socketReader.InputStreamOptions = InputStreamOptions.Partial;

My possibly incorrect understanding of the await keyword is that the call is basically put on a new thread and that the rest of the function will continue off on the previous thread. Since the DataReader was declared locally, it will go out of scope once the function completes, leaving the await thread to work off of a disposed object.

If anybody wants to clarify this it would be appreciated.

1

Based of Alex Sorokoletov's last comment, my guess would be that the one of your important objects (probably the stream) would be disposed in the call to datareader.DetachStream();

Noémie Lord
  • 751
  • 4
  • 22