UDP 异步 - 为什么要创建一个新的 UdpClient

UDP async - Why make a new UdpClient

class UdpExample
{
    private UdpClient Client = new UdpClient(25971);

    public UdpExample()
    {
        Client.BeginReceive(DataReceived, Client);
    }

    private void DataReceived(IAsyncResult ar)
    {
        UdpClient c = (UdpClient)ar.AsyncState
        IpEndPoint receivedIpEndPoint = new IpEndPoint(IpAddress.Any, 0);
        Byte[] data = c.EndReceive(ar, ref receivedIpEndPoint);
    }
}

在上面的代码中,为什么一个新的UdpClient(c)是由ar.AsyncState生成的? 为什么它不能只使用 Client.EndReceive(使用类范围 UdpClient

ar.AsyncStateobject,不是 new UdpClient,是 you ] 通过了

为什么?因为如果你周围有很多这样的东西,你就知道你在处理哪个,但是它不仅可以用于 UdpClient 你可以传入任何东西,并且确定它属于 Begin 你开始了。

我们来看documentation

中的参数

state Object - A user-defined object that contains information about the receive operation. This object is passed to the requestCallback delegate when the operation is complete.