Truman Starr Truman Starr - 2 months ago 7
C# Question

Await doesn't give a result

Ok, I have some code to present. Here is extension method for

NetworkStream
object.

public async static Task<byte[]> ReadDataAsync(this NetworkStream clientStream)
{
byte[] data = {};

var buffer = new byte[1024];
if (clientStream.CanRead)
{
using (var ms = new MemoryStream())
{
try
{
int bytesRead;
while (clientStream.DataAvailable &&
(bytesRead = await clientStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await ms.WriteAsync(buffer, 0, bytesRead);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return data;
}

data = ms.ToArray();
}
}
else
{
Console.WriteLine("Closing clientStream.");
clientStream.Close();
}
return data;
}


And the code where I am trying to call this method.

public async static Task Preform(Socket client)
{
var stream = new NetworkStream(client);
var data = await stream.ReadDataAsync();
var message = await MessageFabrique.DeserializeMessage(data);

ServerCollections.Instance.ServerIssueQueue.Add(new ServerIssue
{
Message = message,
ClientStream = stream
});
}


ReadDataAsync
method always returns me to an empty array. And at the moment when i'm trying to deserialize data there is an exception - because
data[0]
. Please help me. Why is this happening, if
await
guarantees me the result, when it needed?

Answer

clientStream.DataAvailable does not mean data might show up in the future. It means data is available right now for reading. Get rid of it and just read, the read will block till data shows up or will return 0 when the stream hits it's end.