Family
Family

Reputation: 1113

ReadAsync exiting, not able to trace in debug

I have the following code (_ns is a NetworkStream)

await GetResponse(_ns);
btnSend.Enabled = true;

private async Task GetResponse(NetworkStream stream)
{
    while (true)
    {
        var readBuffer = new byte[4096];
        var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);
        txtBoxMessagesIn.Text += Encoding.ASCII.GetString(readBuffer.ToArray()) + Environment.NewLine;
        if (asyncReader <= 0) break;
    }
}

I seem to fill the entire buffer with what I expect, but btnSend is never enabled.

When I run it in debug mode, my while loop runs a couple of times, I see asyncReader get set to different values but it never equals 0 to break the loop as I expect, it justs exits at the line:

var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length);

without generating any errors. What is causing this? Do I need to set something in Visual Studio to break on this type of error?

Upvotes: 1

Views: 253

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 456527

ReadAsync will only return 0 when the stream ends. This is how all streams work. If the stream has not ended (i.e., for a socket stream, the socket is still open), then ReadAsync will (asynchronously) wait for the stream to either read more bytes or end.

I assume that the other end of the socket is just hanging open but not sending any more data. In this case, any stream reads will just wait for it to either send more bytes or close. There's no exceptions - this is not an exceptional situation. Since the socket is not closed, the stream read will not return 0, and so your while loop will not exit.

Upvotes: 3

Tomislav Markovski
Tomislav Markovski

Reputation: 12346

You can either wrap the call to ReadAsync in a try/catch statement or check the result of the task. I would go with try/catch approach to at least see what's going on initially.

try { var asyncReader = await stream.ReadAsync(readBuffer, 0, readBuffer.Length); }
catch (Exception ex) { }

Other approach would be the following, but you can't be sure if ReadAsync ends gracefully when exception occurs.

var task = stream.ReadAsync(readBuffer, 0, readBuffer.Length);
task.Start();
if (task.Exception != null)
   // see what's going here

Upvotes: 0

Related Questions