Search code examples
c#socketsasync-awaitsocketasynceventargs

C# SocketAsyncEventHandler evaluate operation on Complete


How do you evaluate if a Socket operation was successful or not with SocketAsyncEventArgs? Do you evaluate the SocketAsyncEventArgs you passed as parameter?

SocketasyncEventArgs saea = new SocketAsyncEventArgs();
socket.ConnectAsync(saea);
saea.Completed += (sender, args) => 
{
    if(saea.SocketError != SocketError.Success)
        // fail
}

Or do you evaluate the SocketAsyncEventArgs from the Completed event?

saea.Completed += (sender, args) => 
{
    if(args.SocketError != SocketError.Success)
        // fail
}

Or both? What does it mean if one shows success and the other not?


Solution

  • Firstly, note that you need to subscribe the event before you call the *Async method (ConnectAsync in this case), and you must check the return value from the *Async method - the true vs false indicates whether it completed synchronously or not; if it completes synchronously, it will not invoke your callback - it is expected that you will invoke any required code.

    As for the question: use the args in the event. The main reason for this is efficiency; the first example uses a "captured variable", which means it needs a capture context instance and a delegate instance per subscription. The second example does not use a captured variable, and as such the compiler optimizes the delegate creation to use a single static event handler instance for all subscriptions.