将参数传递给 AsyncCallback 函数? [英] Pass argument to AsyncCallback function?

查看:36
本文介绍了将参数传递给 AsyncCallback 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习套接字编程,我有以下功能:

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);

问题是我需要向 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆