I’m writing a wrapper class around a TcpClient which raises an event when data arrives. I’m using BeginRead and EndRead, but when the parent form handles the event, it’s not running on the UI thread. I do I need to use delegates and pass the context into the callback? I thought that callbacks were a way to avoid this…
void ReadCallback(IAsyncResult ar)
{
int length = _tcpClient.GetStream().EndRead(ar);
_stringBuilder.Append(ByteArrayToString(_buffer, length));
BeginRead();
OnStringArrival(EventArgs.Empty);
}
The parent form should be using the
Invokemethod on its controls in the event handler to ensure it’s on the right thread; it’s not the job of your background process to conform to what the UI needs. This msdn page has an example.