Pass argument to AsyncCallback function?

This is a problem I prefer to solve with anonymous delegates:

var someDataIdLikeToKeep = new object();
mySocket.BeginBlaBla(some, other, ar => {
        mySocket.EndBlaBla(ar);
        CallSomeFunc(someDataIdLikeToKeep);
    }, null) //no longer passing state as we captured what we need in callback closure

It saves having to cast a state object in the receiving function.


I'm going to presume you're using System.Net.Sockets.Socket here. If you look at the overloads of BeginReceive you'll see the object parameter (named state). You can pass an arbitrary value as this parameter and it will flow through to your AsyncCallback call back. You can then acess it using the AsyncState property of IAsyncResult object passed into your callback. Eg;

public void SomeMethod() {
  int myImportantVariable = 5;
  System.Net.Sockets.Socket s;
  s.BeginReceive(buffer, offset, size, SocketFlags.None, new new AsyncCallback(OnDataReceived), myImportantVariable);
}

private void OnDataReceived(IAsyncResult result) {
  Console.WriteLine("My Important Variable was: {0}", result.AsyncState); // Prints 5
}