将参数传递给AsyncCallback函数? [英] Pass argument to AsyncCallback function?
问题描述
我正在学习套接字编程,并且具有以下功能:
I'm learning socket programming and I have the following function:
public void OnDataReceived(IAsyncResult asyn)
这是设置回调的方式:
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
问题是我需要将另一个参数传递给OnDataReceived回调函数,我该怎么做?我正在尝试制作一个简单的tcp服务器,我需要跟踪数据来自哪个客户端.有小费吗?谢谢!
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!
推荐答案
我假设您在此处使用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
}
这篇关于将参数传递给AsyncCallback函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!