tags:

views:

45

answers:

2

Hi All I want to read from a socket in an asynchronous way.

If I used the synchronous code below

StreamReader aReadStream = new StreamReader(aStream);
String aLine = aReadStream.ReadLine(); // application might hand here

with a valid open connection, but no data available for reading, the application would hang at the ReadLine() function.

If I switch to the code below using Asynchronous Programming Model

NetworkStream aStream = aClient.GetStream();
while(true)
{
     IAsyncResult res = aStream.BeginRead(data, 0, data.Length, null, null);
     if (res.IsCompleted){
          Trace.WriteLine("here");                            
     } else {
          Thread.Sleep(100);
     }
}

In the same scenario what would happen? If there is no data to read, the variable res would appear as Completed or not?

Most important, when there is no data to read, all of my calls in that while loop to aStream.BeginRead() are they scheduled continuously in the Thread Pool? If this is true am I risking to degrade the application performances because the Thread Pool has increased too much its size?

Thanks for the help

AFG

+2  A: 

By writing the code in this way, you've basically made it synchronous.

The proper way to make this code work is to call BeginRead, passing a callback handler which will process the data which has been read when it is ready, then go do other work rather than just entering a loop.

The callback handler you specify will also be triggered when the data stream is terminated (e.g. because the connection was closed) which you can handle appropriately.

See http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread.aspx for a sample.

EricLaw -MSFT-
A: 

Have a look at this article which I wrote that covers asynchronous sockets here on CodeProject which is what I learnt from the "MSDN, August 2005, 'Winsock - Get closer to the wire with high-performance sockets in .NET', Daryn Kiely, Pg 81."

Hope this helps, Best regards, Tom.

tommieb75