Search code examples
c#asp.netsocketsasp.net-web-api

A non-blocking socket operation could not be completed immediately


private void DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
{
    SocketsTelemetry.Log.ConnectStart(socketAddress);
    SocketError errorCode;
    try
    {
        errorCode = SocketPal.Connect(_handle, socketAddress.Buffer.Slice(0, socketAddress.Size));
    }
    catch (Exception ex)
    {
        SocketsTelemetry.Log.AfterConnect(SocketError.NotSocket, ex.Message);
        throw;
    }

    // Throw an appropriate SocketException if the native call fails.
    if (errorCode != SocketError.Success)
    {
        UpdateConnectSocketErrorForDisposed(ref errorCode);
        // Update the internal state of this socket according to the error before throwing.
        SocketException socketException = SocketExceptionFactory.CreateSocketException((int)errorCode, endPointSnapshot);
        UpdateStatusAfterSocketError(socketException);
        if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, socketException);

        SocketsTelemetry.Log.AfterConnect(errorCode);

        throw socketException;
    }

    SocketsTelemetry.Log.AfterConnect(SocketError.Success);

    if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"connection to:{endPointSnapshot}");

    // Update state and performance counters.
    _pendingConnectRightEndPoint = endPointSnapshot;
    _nonBlockingConnectInProgress = false;
    SetToConnected();
    if (NetEventSource.Log.IsEnabled()) NetEventSource.Connected(this, LocalEndPoint, RemoteEndPoint);
}

In my asp.net web API project when i run the Login API at that time Socket.cs file throwing error: "A non-blocking socket operation could not be completed immediately." in the above code block. What should i do?


Solution

  • I found the solution to the socket blocking error. The issue was due to 'An operation on a nonblocking socket cannot be completed immediately'. The error occurred because I wasn't using await when fetching data (DB connection). Without await, the code likely took a bit of time, causing the socket error. After adding await, the issue was resolved. like this: var users = await _dbContext.AspNetUsers.FirstOrDefaultAsync(u => u.Email == Credentials.Email); If anyone else is facing the same issue, you can resolve it similarly by ensuring you use await where appropriate.