【问题标题】:When should I use UdpClient.BeginReceive? When should I use UdpClient.Receive on a background thread?什么时候应该使用 UdpClient.BeginReceive?我什么时候应该在后台线程上使用 UdpClient.Receive?
【发布时间】:2011-08-08 18:54:05
【问题描述】:

本质上,这些之间的区别是什么?什么时候应该使用哪种形式?

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

【问题讨论】:

    标签: .net asynchronous begininvoke asynccallback


    【解决方案1】:

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

    你当然可以简介...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 2012-09-22
      • 1970-01-01
      • 2023-04-02
      • 2011-04-15
      • 2017-04-10
      • 2012-03-19
      相关资源
      最近更新 更多