Hey folks,
So I decided to try to code in c# instead of vb. You know - using a real language. However, I've hit one wall. I'm building a chat client (IM type thing), which contains a loop that runs for as long as the client is connected. Naturally, that loop runs in a seperate thread. However, the loop is checking for new messages from the server. I've tried using invoke to call a method in the main thread to handle received messages, but it's not working right. Here's what I've got that's relevant.
The invoke call:
Code:
this.Invoke(new UpdateLogCallback(UpdateLog), new object[] { srReceiver.ReadLine() });
I also tried this for invoke:
Code:
txtLog.Invoke(new UpdateLogCallback(UpdateLog), new object[] { srReceiver.ReadLine() });
Defined in the class:
Code:
private delegate void UpdateLogCallback(string strMessage);
Code:
private void UpdateLog(string strMessage)
{
txtLog.AppendText(strMessage + "\r\n");
}
Can anyone spot what I'm doing wrong? I've also tried with a static string, and have tried stepping through the code. The error comes from the invoke call, not its content, and reads thus:
InvalidOperationException was caught:
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
I'm using a try-catch block to stop the thing crashing, but whilst it connects (the server part (which just uses 1 thread because it doesn't need to do anything but listen after it starts doing so) reports the connection being made, and step through of client code confirms it happened) it doesn't get recorded in the textbox. Could someone help? I can post more code if needed.