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!
This is a problem I prefer to solve with anonymous delegates:
It saves having to cast a state object in the receiving function.
When you call
BeginReceive
, you can pass anyobject
as its last parameter. The same object will be made available to your callback throughIAsyncResult
'sAsyncState
property.I'm going to presume you're using
System.Net.Sockets.Socket
here. If you look at the overloads of BeginReceive you'll see theobject
parameter (named state). You can pass an arbitrary value as this parameter and it will flow through to yourAsyncCallback
call back. You can then acess it using theAsyncState
property ofIAsyncResult
object passed into your callback. Eg;