-->

When should I use UdpClient.BeginReceive? When sho

2019-05-11 14:02发布

问题:

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