更新时间: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
}