我什么时候应该使用 UdpClient.BeginReceive?我什么时候应该在后台线程上使用 UdpClient.Receive?
从本质上讲,除了明显的区别之外,它们之间还有哪些区别?我什么时候应该使用哪种形式?
class What
{
public Go()
{
Thread thread = new Thread(new ThreadStart(Go2));
thread.Background = true;
thread.Start();
}
private Go2()
{
using UdpClient client = new UdpClient(blabla)
{
while (stuff)
{
client.Receive(guh);
DoStuff(guh);
}
}
}
}
相对
class Whut
{
UdpClient client;
public Go()
{
client = new UdpClient(blabla);
client.BeginReceive(guh, new AsyncCallback(Go2), null);
}
private Go2(IAsyncResult ar)
{
client.EndReceive(guh, ar);
DoStuff(guh);
if (stuff) client.BeginReceive(guh, new AsyncCallback(Go2), null);
else client.Close();
}
}
Essentially, what are the differences between these beyond the obvious? When should I use which form?
class What
{
public Go()
{
Thread thread = new Thread(new ThreadStart(Go2));
thread.Background = true;
thread.Start();
}
private Go2()
{
using UdpClient client = new UdpClient(blabla)
{
while (stuff)
{
client.Receive(guh);
DoStuff(guh);
}
}
}
}
versus
class Whut
{
UdpClient client;
public Go()
{
client = new UdpClient(blabla);
client.BeginReceive(guh, new AsyncCallback(Go2), null);
}
private Go2(IAsyncResult ar)
{
client.EndReceive(guh, ar);
DoStuff(guh);
if (stuff) client.BeginReceive(guh, new AsyncCallback(Go2), null);
else client.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为差异通常不会很大,但如果我希望传入流中出现暂停,那么我更喜欢完全异步方法(开始.../结束...),以便可以将回调卸载几层而不是要求额外的线程。异步方法的另一个优点是,您始终可以获取所需的数据,对另一个异步获取进行排队,然后在现有异步线程上处理新数据,从而提供更多并行性选项(一读,一次处理)。当然,这也可以手动完成(也许使用工作队列)。
您当然可以配置文件...
I don't think the difference will usually be huge, but I would prefer the full async approach (Begin.../End...) if I expect pauses in the incoming stream, so that the callback can be offloaded a few layers rather than demanding an extra thread. Another advantage of the async approach is that you can always get the data you need, queue another async fetch, and then process the new data on the existing async thread, giving some more options for parallelism (one reading, one processing). This can be done manually too, of course (perhaps using a work queue).
You could of course profile...