13

I'm learning socket programming and I have the following function:

public void OnDataReceived(IAsyncResult asyn)

and this is how the callback gets set:

pfnWorkerCallBack = new AsyncCallback(OnDataReceived);

The problem is I need to pass another argument to OnDataReceived callback function, how can I do this? I'm trying to make a simple tcp server and I need to track from which client the data is coming from. Any tips? Thanks!

Yahia
  • 69,653
  • 9
  • 115
  • 144
user1192403
  • 597
  • 2
  • 5
  • 19
  • [Asynchronous Delegates Programming Sample](http://msdn.microsoft.com/en-us/library/h80ttd5f.aspx) – sll Feb 08 '12 at 11:50

4 Answers4

10

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
}
MrMDavidson
  • 2,705
  • 21
  • 20
4

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.

spender
  • 117,338
  • 33
  • 229
  • 351
2

When you call BeginReceive, you can pass any object as its last parameter. The same object will be made available to your callback through IAsyncResult's AsyncState property.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

As MrMDavidson mentioned.

If you look at the overloads of BeginReceive you'll see the object parameter (named state)

You could pass an object array of your desired parameters to the state parameter and then deal with them later in the callback method.

client.BeginConnect(ipEndPoint, new AsyncCallback(ConnectedCallback), new object[] { parameter1, parameter2});
Majx
  • 131
  • 14