private void Receive()
{
try
{ if ( callbackProc == null )
callbackProc = new
AsyncCallback(ReceiveCallback);
StateObject state=new StateObject();
state.workSocket = s;
s.BeginReceive(state.buffer,
0, StateObject.BufferSize,
SocketFlags.None,
callbackProc, state);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiveCallback (IAsyncResult ar)
{
try
{
StateObject state = (StateObject)
ar.AsyncState;
int bytesRead =
state.workSocket.EndReceive(ar);
string szData =
System.Text.Encoding.Unicode.GetString(state.buffer, 0, bytesRead);
frmNew n = new frmNew();
n.show();
Receive();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Requires Free Membership to View
When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to provide a unique online resource for developers, architects and development managers tasked with building and maintaining enterprise applications using Visual Basic, C# and the Microsoft .NET platform.
Hannah Smalltree, Editorial Director
delegate void ShowDelegate();
private void ReceiveCallback (IAsyncResult ar)
{
try
{
//do your work
frmNew n = new frmNew();
this.Invoke(new ShowDelegate(n.Show));
//the rest goes here
I'm assuming your callback method is placed on the main form; that's why I use this.Invoke, but that's not a requisite. As long as you can get a reference to it (through a static variable or whatever), it's OK.
This was first published in October 2003