Tcpclient infinite loop

private void DoRead(IAsyncResult ar)
{
int BytesRead;
try
{
BytesRead = client.GetStream().EndRead(ar);

if ((BytesRead < 1))
{
Finished = true;
return;
}
strHTML += Encoding.ASCII.GetString(readBuffer, 0, (BytesRead - 2));

BytesRead = 0;
client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new System.AsyncCallback(this.DoRead), null);


}
catch (Exception)
{
// Future Handle
}
}

I call it like this:

client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
while (Finished != true)
{
Application.DoEvents();
}
Finished = false;

The problem is that once it's finished reading the data it continuosly jumps from the last beginread to the end of the function. I ran it through in debug mode and once it reads the last bit of data BytesRead somehow gets stuck at 255 and it loops continusosly from
client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new System.AsyncCallback(this.DoRead), null); to the last }.
I tried putting client.GetStream().DataAvailable, but then if there is a small amount of time where this isn't any data it stops.

Thanks for any help
[1656 byte] By [cx323] at [2007-11-20 0:03:40]
# 1 Re: Tcpclient infinite loop
cx323,

according to MSDN:
"Calling this method (DoEvents) can cause code to be re-entered if a message raises an event."

So that may be your problem.

I would like to make a statement regarding your code. If you are making an asynchronous function call, then you should have NO NEED to use doevents. If you need to set Finished = false after the call completes, you can simply do that in a function which gets called after your asynchronous call completes.

See if that helps you.
hedge_fund at 2007-11-9 11:24:31 >
# 2 Re: Tcpclient infinite loop
thanks for the help, the problem went away when i got rid of doevents
cx323 at 2007-11-9 11:25:31 >