infinite NetworkStream (CPU consuming)

  • Thread starter Thread starter psg
  • Start date Start date
P

psg

Hello!

I am developing Windows application which after sending a request to a
server will listen to response, a response will be infinite in length, but
will not be continuous in time.

What I have done is in a back thread I prepared infinite loop and there I am
checking for new packages. Its scheme looks like this:

***********************************
while(shallRun)
{
loopCounter++;

while(networkStream.DataAvailable)
{
networkStream.Read(buffer, 0, buffer.Length);

packagesCounter++;

//do some data manipulation here
//UpdateUI
}
}
***********************************

Unfortunatelly for every package my program is doing thousands or even
million "empty" loops. Probably that is why CPU is very high, and can even
get to 100%.

Do you know some other C# solution for reading infinite NetworkStream. Some
event OnNewData? or maybe some other solutions.

TIA

RGDS PSG
 
psg,

I would use the BeginRead and EndRead methods to do this. The
information that is coming to you is in groups of bytes that compose a
message, and you are performing some action based on that message. When you
start listening, you
call BeginRead, trying to read the message from the socket.

In the event handler for the callback to BeginRead, you can get the
message. If you require more bytes for the message, then read as much as
you need for that particular message. Process the message, and then kick
off another call to BeginRead at the end, starting it all over again. This
way, your callback will be notified when you have a new message to process,
and it will place itself in a state to receive the next one.

Hope this helps.
 
Nicholas Paldino said:
I would use the BeginRead and EndRead methods to do this.

I thought that it would be too hard to do but finally I got it right.
Frankly speaking now I combined two methods BeginRead and Read. When waiting
for new message (seeking for new message beginning) I use BeginRead, when
processing message and working with known length of packages I use Read, but
now it doesn't use CPU at all, because with your help I got rid off that
erroneous "empty" loop. THX!

RGDS PSG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top