When should I use UdpClient.BeginReceive? When should I use UdpClient.Receive on a background thread?

柔情痞子 提交于 2020-01-02 07:07:15

问题


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

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



来源:https://stackoverflow.com/questions/5718674/when-should-i-use-udpclient-beginreceive-when-should-i-use-udpclient-receive-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!