TcpClient.EndConnect throws a NullReferenceException when closing a socket

I am trying to connect to my server using a command TcpClient.BeginConnect / TcpClient.EndConnect. However, some things do not work as they should.

The scenario is as follows:

  • Call TcpClient.BeginConnect
  • The server is intentionally down (for testing purposes) - thus, the connection cannot be made.
  • Close the application ( client.Close()called in a process that closes the socket, which in turn stops the async operation )
  • TcpClientconnection callback method occurs when providedIAsyncResult
  • Call a method TcpClient.EndConnectwith a givenIAsyncResult
  • NullReferenceExceptionoccurs on EndConnect( ? )
  • Since the last form (window) was closed, the application should exit, but this is not so, at least until the operation BeginConnectis completed (which is strange, since callback has already been called).

exception

What happens is what is NullReferenceExceptioncaught. As can be seen from the figure above, neither client, nor arare null. The problem is that the MSDN documentation for EndConnect does not mention the case in which this exception is thrown.

Basically, I have no idea what is going on. The problem is that I have to wait for the application to close (as if the connection operation is still waiting for a timeout). If the server is connected to the network, it connects and disconnects perfectly.

NullReferenceException ? BeginConnect ?


( ):

( -:

public void Connect()
{
    try
    {
        lock (connectionAccess)
        {
            if (State.IsConnectable())
            {
                // Create a client
                client = new TcpClient();
                client.LingerState = new LingerOption(false, 0);
                client.NoDelay = true;

                State = CommunicationState.Connecting;

                client.BeginConnect(address, port, onTcpClientConnectionEstablished, null);
            }
            else
            {
                // Ignore connecting request if a connection is in a state that is not connectable 
            }
        }
    }
    catch
    {
        Close(true);
    }
}

Close:

public void Close(bool causedByError)
{
    lock (connectionAccess)
    {
        // Close the stream
        if (clientStream != null)
            clientStream.Close();

        // Close the gateway
        if (client != null)
            client.Close();

        // Empty the mailboxes
        incomingMailbox.Clear();
        outgoingMailbox.Clear();

        State = causedByError ? CommunicationState.CommunicationError : CommunicationState.Disconnected;
    }
}
+5
4

NullReferenceException, , , TcpClient.Client null.

MSDN Example TcpClient.BeginConnect TcpClient :

 private void onConnEst(IAsyncResult ar)
 {
      try
      {
           TcpClient client = (TcpClient)ar.AsyncState;
           if(client!=null && client.Client!=null)
           {
                client.EndConnect(ar);
           }
      }
      catch(Exception ex){...}
 }

, Close() .

- ?

+1

, , TcpClient. . TcpClient.Dispose Client null, EndConnect .

+1

, . , IASyncResult, . , ar.AsyncState == null, , , , .. ?

private void connConnectCompleted(AsyncCompletedEventArgs e)
{
    if (e.Error != null)
    {
        // Something didn't work...abort captain
        CloseSocket();
        Console.WriteLine(this.GetType().ToString() + @":Error connecting socket:" +  e.Error.Message);
        return;
    }
    // Do stuff with your connection
}

EDIT: , , , AsyncCompletedEventArgs, , . , , ar.AsyncState null.

private void OnConnect(IAsyncResult asyncResult)
{
    if (OnConnectCompleted == null) return; // Check whether something is using this wrapper
    AsyncCompletedEventArgs args;
    try
    {
        Socket outSocket = (Socket) asyncResult.AsyncState;

        // Complete connection
        outSocket.EndConnect(asyncResult);

        args = new AsyncCompletedEventArgs(null);
        OnConnectCompleted(this, args);
    }
    catch (Exception e)
    {
        args = new AsyncCompletedEventArgs(e.Message);
        OnConnectCompleted(this, args);
    }
}
0
source

This is a search error .

You should get an "ObjectDisposedException" instead of a "NullReferenceException".

0
source

All Articles