How do you 'cancel' a UdpClient::BeginReceive?

我与影子孤独终老i 提交于 2019-12-01 04:50:49

You need to jerk the floor mat, call the UdpClient.Close() method.

That will complete the BeginReceive() call and your callback method will run. When you call EndReceive(), the class lets you know the floor mat is gone and will throw an ObjectDisposedException. So be prepared to handle this exception, wrap the EndReceive() call with try/catch so you catch the ODE and just exit the callback method.

Do note that this tends to get .NET programmers a bit upset, using exceptions for flow control is in general strongly discouraged. You however have to call EndInvoke(), even if you already know that this going to throw an exception. Failure to do so will cause a resource leak that can last a while.

EgoPingvina

For the canceling BeginRecieve you can use Close method, but in base realization it will invoke ObjectDisposedException. I fixed it with creating custom BeginRecieve which is modernization of base realization:

public Task<UdpReceiveResult> ReceiveAsync(UdpClient client, CancellationToken breakToken)
    => breakToken.IsCancellationRequested
        ? Task<UdpReceiveResult>.Run(() => new UdpReceiveResult())
        : Task<UdpReceiveResult>.Factory.FromAsync(
            (callback, state) => client.BeginReceive(callback, state),
            (ar) =>
                {
                    if (breakToken.IsCancellationRequested)
                        return new UdpReceiveResult();

                    IPEndPoint remoteEP = null;
                    var buffer = client.EndReceive(ar, ref remoteEP);
                    return new UdpReceiveResult(buffer, remoteEP);
                },
            null);

More read here: UdpClient.ReceiveAsync correct early termination.

Also will be helpfull this: Is it safe to call BeginXXX without calling EndXXX if the instance is already disposed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!