你怎么'取消'一UdpClient :: BeginReceive? [英] How do you 'cancel' a UdpClient::BeginReceive?

查看:289
本文介绍了你怎么'取消'一UdpClient :: BeginReceive?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程,坐在那里等待来自多个接口的UDP报文使用 UdpClient :: BeginReceive 和回调这就要求 UdpClient :: EndReceive 拿起数据,并通过它。

I have a thread which sits around waiting for UDP messages from multiple interfaces using UdpClient::BeginReceive and a callback which calls UdpClient::EndReceive to pick up the data and pass it on.

如果5秒后我没有得到任何东西,我从中调用该函数返回 UdpClient :: BeginReceive 这样的过程可以被取消,并发出另一个广播这将触发外部客户端发送的UDP响应。如果我们不取消,我再次拨打了 UdpClient :: BeginReceive 函数来检查新的数据。

If after 5 seconds I don't get anything, I return from the function which calls UdpClient::BeginReceive so that the process can be cancelled and to issue another broadcast which would trigger external clients to send in UDP responses. If we're not cancelling, I call the UdpClient::BeginReceive function again to check for new data.

如果客户端没有收到任何数据的时候,有没有办法来取消异步请求,而无需调用 EndReceive 哪些块下去?我得到的IM pression是造成数百异步的触发运行将是一个坏主意。

If the client hasn't received any data in time, is there a way to cancel that async request without calling EndReceive which blocks indefinitely? I get the impression that leaving hundreds of async triggers running would be a bad idea.

推荐答案

您需要挺举的地板垫,调用UdpClient.Close()方法。

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

这将完成BeginReceive()调用和回调方法运行。当你调用EndReceive(),这个类可以让你知道的地垫是走了,将抛出的ObjectDisposedException。所以要ppared来处理这个异常$ P $,包住EndReceive()与try / catch语句调用,所以你赶上ODE,只是退出回调方法。

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.

请注意,这往往会.NET程序员有点不高兴,使用异常流量控制在一般强烈反对。但是,您的有无的调用EndInvoke会(),即使你已经知道这会抛出异常。如果不这样做会造成资源泄漏可能持续一段时间。

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.

这篇关于你怎么'取消'一UdpClient :: BeginReceive?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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