How can I safely raise events in an AsyncCallback?

Posted by cyclotis04 on Stack Overflow See other posts from Stack Overflow or by cyclotis04
Published on 2010-05-27T06:15:48Z Indexed on 2010/05/27 6:21 UTC
Read the original article Hit count: 297

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about events