什么时候应该使用UdpClient.BeginReceive?什么时候应该使用UdpClient.Receive在后台线程? [英] When should I use UdpClient.BeginReceive? When should I use UdpClient.Receive on a background thread?

查看:714
本文介绍了什么时候应该使用UdpClient.BeginReceive?什么时候应该使用UdpClient.Receive在后台线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从本质上讲,有什么明显超出它们之间的区别是什么?什么时候应该使用哪种形式?

 类是什么
{
    公共围棋()
    {
        线程线程=新主题(新的ThreadStart(GO 2));
        thread.Background = TRUE;
        thread.Start();
    }
    私人GO2()
    {
        使用UdpClient客户端=新的UdpClient(布拉布拉)
        {
            而(东东)
            {
                client.Receive(GUH);
                DoStuff(GUH);
            }
        }
    }
}
 

 武汉理工类
{
    UdpClient客户端;
    公共围棋()
    {
        客户端=新的UdpClient(布拉布拉);
        client.BeginReceive(GUH,新的AsyncCallback(GO2),NULL);
    }
    私人GO2(IAsyncResult的AR)
    {
        client.EndReceive(GUH,AR);
        DoStuff(GUH);
        如果(东西)client.BeginReceive(GUH,新的AsyncCallback(GO2),NULL);
        别的client.Close();
    }
}
 

解决方案

我不认为差异通常是巨大的,但我会preFER完整的异步方法(...开始/结束... )如果我期望输入流中的暂停,以便回调可以被卸载几层而不是要求一个额外的螺纹。异步方法的另一个好处是,你总是可以得到你所需要的数据,队列另一个异步读取,然后处理上的现有的异步线程,从而并行一些更多的选择,新的数据(一个读,一个处理)。这可以手工完成也当然(也许使用工作队列)。

您当然可以配置文件...

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();
    }
}

解决方案

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...

这篇关于什么时候应该使用UdpClient.BeginReceive?什么时候应该使用UdpClient.Receive在后台线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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