为什么这个参数是空的?

时间:2017-02-06 09:23:05

标签: c#

public static void Connect(EndPoint remoteEP, Socket client) {
    client.BeginConnect(remoteEP, 
        new AsyncCallback(ConnectCallback), client );

   connectDone.WaitOne();
}

private static void ConnectCallback(IAsyncResult ar) {
    try {
        // Retrieve the socket from the state object.
        Socket client = (Socket) ar.AsyncState;

        // Complete the connection.
        client.EndConnect(ar);

        Console.WriteLine("Socket connected to {0}",
            client.RemoteEndPoint.ToString());

        // Signal that the connection has been made.
        connectDone.Set();
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}

您好,我对上面两个函数有疑问 在函数“client.BeginConnect”中,为什么ConnectCallback的参数为空? ConnectCallback函数有参数(IAsyncResult ar)。但是BeginConnect不会调用此参数..谁可以回答我的问题?

2 个答案:

答案 0 :(得分:2)

BeginConnect方法需要将委托引用作为第二个参数传递,该参数将在异步任务完成时调用。如果您为ConnectCallback指定了一个参数,那么它将被评估为方法调用,其结果将是void(因为它是一个无效的方法),因此您的代码不会&# 39; t compile。

换句话说,如果您有这样的方法:

void DoStuff(int parameter)
{ ... }

然后将引用DoStuff

相区别
// method variable will get the reference to the DoStuff method
Action<int> method = new Action<int>(DoStuff);

// invoking the delegate will invoke the actual DoStuff method
method(7);

调用方法(评估它):

// this will simply evaluate DoStuff
DoStuff(7);

传递给异步方法的委托称为&#34;回调&#34;,因为异步方法应该在完成其工作后调用它们。在这种情况下,传递给回调委托的实际参数将从异步方法传递,或者由方法创建,或者在某个时间之前由您自己提供。

如果是BeginConnect,您还会传递state参数,这是将传递给您的回调的实际参数,这意味着Socket.BeginConnect在功能上与此类似,引擎盖:

void BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
{
    // create an async task and return to called immediately
    Task.Run(() => 
    {
         // do some stuff on a background thread
         ....

         // call `callback` when done, and pass the `state` parameter
         // through the `IAsyncResult` parameter
         var result = new ConnectAsyncResult(..., state, ...);
         callback(result);
    });
}

你的回调方法的责任是在传递的参数上调用EndInvoke来完成操作。

此模式使您的调用代码能够继续执行,并使用有关实际调用它的所有必要信息(&#34;状态&#34;)来接收通知。

答案 1 :(得分:0)

AsyncCallback是一个委托,它将执行以IAsyncResult为参数的回调方法。您可以看到说明here。所以基本上你需要提供一个接受IAsyncResult作为参数的方法,以便AsyncCallback委托调用它,在你的情况下是你的ConnectCallback方法