Pass argument to AsyncCallback function?

我的未来我决定 提交于 2019-12-05 01:27:37

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
}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!