【问题标题】:Pass argument to AsyncCallback function?将参数传递给 AsyncCallback 函数?
【发布时间】:2012-02-29 20:14:44
【问题描述】:

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

public void OnDataReceived(IAsyncResult asyn)

这就是设置回调的方式:

pfnWorkerCallBack = new AsyncCallback(OnDataReceived);

问题是我需要将另一个参数传递给 OnDataReceived 回调函数,我该怎么做?我正在尝试制作一个简单的 tcp 服务器,我需要跟踪数据来自哪个客户端。有小费吗?谢谢!

【问题讨论】:

标签: c# function arguments asynccallback


【解决方案1】:

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

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
}

【讨论】:

  • @user1192403 很高兴听到它:)
  • 如果我们要传递多个参数怎么办?
  • 那你就得使用某种容器了; public class Foo { public int Bar {get;set;} public string Baz {get;set;} } 然后将其实例传递给BeginReceive 方法并将result.AsyncState 转换回该类型。
【解决方案2】:

这是我更喜欢用匿名代表解决的问题:

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

它不必在接收函数中强制转换状态对象。

【讨论】:

    【解决方案3】:

    当您调用BeginReceive 时,您可以传递任何object 作为其最后一个参数。相同的对象将通过IAsyncResultAsyncState 属性提供给您的回调。

    【讨论】:

      【解决方案4】:

      正如 MDavidson 先生所说。

      如果您查看 BeginReceive 的重载,您会看到对象参数(命名状态)

      您可以将所需参数的对象数组传递给state 参数,然后稍后在回调方法中处理它们。

      client.BeginConnect(ipEndPoint, new AsyncCallback(ConnectedCallback), new object[] { parameter1, parameter2});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-01-27
        • 2021-04-18
        • 1970-01-01
        • 2014-02-07
        相关资源
        最近更新 更多