且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将参数传递给AsyncCallback函数?

更新时间:2022-06-27 02:41:02

我假设您在此处使用System.Net.Sockets.Socket.如果您查看 BeginReceive 的重载,您会看到object参数(命名状态).您可以传递一个任意值作为此参数,它将直接传递给您的AsyncCallback回调.然后,您可以使用传递到回调中的IAsyncResult对象的AsyncState属性访问它.例如;

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
}