views:

35

answers:

1

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);
}
A: 

The parent form should be using the Invoke method 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.

JustABill
But shouldn't the class raise events on the same thread it was created on?
Daniel Rasmussen
Begin*/End* run on a separate thread from everything else; if you look at the Threads view in Visual Studio it'll be called "Asynchronous method runner". The AsyncCallback from the end of one of these will be called by this thread, never the one that started it.
JustABill