I probably wouldn't invoke myself like you're doing.
And, since you *know* the actual type of control in question, why not pass that type to the delegate, or just the text (since you can safely assume that the actual control itself exists)?
You're adding obscurity for the (intended) sake of convenience, and muddying the picture as a result.
public delegate void DelegateTextSetter;
public DelegateTextSetter TextSetter = new DelegateTextSetter(SetText);
public void SetText(string text)
{
myRichTextControl.Text = text;
}
public void OnReceive(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead;
if (handler.Connected)
{
try
{
bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Remove(0, state.sb.Length);
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
Invoke(TextSetter, content);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(OnReceive), state);
}
}
catch (SocketException socketException)
{
if (socketException.ErrorCode == 10054 || ((socketException.ErrorCode != 10004) && (socketException.ErrorCode != 10053)))
{
handler.Close();
}
}
}
}