我什么时候应该使用 UdpClient.BeginReceive?我什么时候应该在后台线程上使用 UdpClient.Receive?

发布于 2024-11-02 10:37:10 字数 872 浏览 0 评论 0原文

从本质上讲,除了明显的区别之外,它们之间还有哪些区别?我什么时候应该使用哪种形式?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗恋未遂 2024-11-09 10:37:10

我认为差异通常不会很大,但如果我希望传入流中出现暂停,那么我更喜欢完全异步方法(开始.../结束...),以便可以将回调卸载几层而不是要求额外的线程。异步方法的另一个优点是,您始终可以获取所需的数据,对另一个异步获取进行排队,然后在现有异步线程上处理新数据,从而提供更多并行性选项(一读,一次处理)。当然,这也可以手动完成(也许使用工作队列)。

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文