المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Threading & StreamReader.Read() Question



C# Programming
04-06-2009, 09:51 PM
Hey guys

I've been battling to get a response from a server using TcpClient. Now finally after 3 days of problems due to the learning curve I'm getting responses from the server http://www.barakasoft.com/script/Forums/Images/smiley_smile.gif

Here is the code at the moment.

private void ReceiveMessages()
{
//
// This method executes in its own thread
try
{
// Get the stream where responses will come from
srReceiver = new StreamReader(tcpServer.GetStream());

string result = string.Empty;

while (Connected)
{
//
// Read the next byte and convert it to a char
char CurrentChar = (char)srReceiver.Read();

//
// if the current character is one of the three Terminators, flag as such
if (CurrentChar == RecordTerminator) // 0x00
{
result += "[Record Terminator]";
}
else if (CurrentChar == FieldTerminator) // 0x01
{
result += "[Field Terminator]";
}
else if (CurrentChar == PacketTerminator) // 0x02
{
result += "[Packet Terminator]";
}
else
{
result += CurrentChar.ToString();
}

if (#########) // Condition??? http://www.barakasoft.com/script/Forums/Images/smiley_confused.gif
{
//
// Send the response back to the main thread
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { result });

//
// Clear the result string
result = string.Empty;
}
}
}
catch (Exception ex)
{
//
// Send exception back to the main thread
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { ex.Message });
}
}

Now one of the weirdness's I came across is that if I try StreamReader.ReadLine() I get empty strings as response.
If I use StreamReader.Read() I get the correct response, one character at a time.

Obviously i cant use the CallBack for every character received as this is way to slow, so what I'd like is to only send the use the callback after all the data has been read. But how do i know when its finished? IE what condition do i need to set instead of the #########? Cause if StreamReader.Read() is called and there is no data, it waits for some.

PS, I cant use the packet terminator as this is not always sent at the end of every packet response

Any ideas?

Harvey Saayman - South Africa
Software Developer
.Net, C#, SQL
you.suck = (you.Passion != Programming & you.Occupation == jobTitles.Programmer)
1000100 1101111 1100101 1110011 100000 1110100 1101000 1101001 1110011 100000 1101101 1100101 1100001 1101110 100000 1101001 1101101 100000 1100001 100000 1100111 1100101 1100101 1101011 111111