c# - async await usage with TcpClient -
i started using new c#5.0 "async" , "await" keywords. thought got twist realized 1 thing made me doubt. here's how asynchronously receiving data remote tcpclient. once accept connection call function :
static async void readasync(tcpclient client) { networkstream ns = client.getstream(); memorystream ms = new memorystream(); byte[] buffer = new byte[1024]; while(client.connected) { int bytesread = await ns.readasync(buffer, 0, buffer.length); ms.write(buffer, 0, bytesread); if (!ns.dataavailable) { handlemessage(ms.toarray()); ms.seek(0, seekorigin.begin); } } }
after data received, loop goes on , on without reading anything. tested console.writeline in loop. using correctly? feel should not using while loop...
the tcpclient.connected
value not updated immediately. according msdn:
true
if client socket connected remote resource of most recent operation; otherwise,false
.
so having tcpclient.connected
while loop condition not choice.
tcpclient.dataavailable
used synchronous operations , not used asynchronous.
update code to:
static async void readasync(tcpclient client) { networkstream ns = client.getstream(); memorystream ms = new memorystream(); byte[] buffer = new byte[1024]; while(true) { int bytesread = await ns.readasync(buffer, 0, buffer.length); if (bytesread <= 0) break; ms.write(buffer, 0, bytesread); handlemessage(ms.toarray()); ms.seek(0, seekorigin.begin); } }
when readasync
return 0, means tcp connection closing or closed. in msdn:
the value of
tresult
parameter contains total number of bytes read buffer. result value can less number of bytes requested if number of bytes available less requested number, or can 0 (zero) if end of stream has been reached.
Comments
Post a Comment