Is C# NetworkStream.Read() a processor efficient waiting mechanism

I have some C# code that reads data from a local socket using the NetworkStream.read() method.

I have the NetworkStream.ReadTimeout set to 'infinite' so it will continue waiting as long as possible for data.
There may be long gaps where there is no data on the socket, so I am worried that I am wasting procesor time in my thread that just sits in a read() waiting for data.
I have a thread dedicated to reading data from the socket, but I still don't want the system giving my thread time-slices if most of the time it is just waiting for data.

The question is, does the NetworkStream.read() internally use a processor efficient mechanism to wait for data, like a mutex or a monitor or some such.

So should I replace the following code:

NetworkStream stream;

...

byte[] onebyte = new byte[1];

// Wait forever until some data is available on the socket
while (1 == stream.Read(onebyte, 0, 1))
{
// Finish reading chunk of data from stream
}

with the following code:

while (true)
{
if (stream.DataAvailable == true)
{
	// Finish reading chunk of data from stream
}
else
{
Thread.Sleep(0);
}
}

Thanks for your help...



Answer this question

Is C# NetworkStream.Read() a processor efficient waiting mechanism

  • bkkandula

    First of all, I dont think that your application is consuming more CPU when its waiting for a blockign operation to finish and go further.

    Yes Your application will consume more CPU when data is coming very fast. And putting Thread.Sleep(0) is just a waste in my sight. You should eleminate that.

    Second thing, In my personal View if you are really concious about CPU usage then you should ofcourse consider Asynchnous operation while reading and writing from NetworkStream.

    "but I still don't want the system giving my thread time-slices if most of the time it is just waiting for data."

    Time slicing will always be there because your application is not the only application which is running on a CPU or 2. Windows Itself needs CPU resources and memory.

    So the Conclusion in my point of view is tha you should seriously think about Asynchonous operations if you need your application to be a resource friendly.

    Its useless to say that when you create more threads yourself there will be more resource usage so why dont you leave them on Windows Thread pool to be managed by Windows (By using Asynchronous Functions

    Best Regards,

    Rizwan aka RizwanSharp



  • Trevor E Hilder

    Yes, underlying it, it uses the Winsock function recv, which does block appropriately. If you're concerned about overall system performance, I think you'll find that using NetworkStream.BeginRead is slightly better, since it takes advantage of IO completion ports, rather than consuming a thread.

  • Is C# NetworkStream.Read() a processor efficient waiting mechanism