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

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())
{
client = new TcpClient();
client.LingerState = new LingerOption(false, 0);
client.NoDelay = true;
State = CommunicationState.Connecting;
client.BeginConnect(address, port, onTcpClientConnectionEstablished, null);
}
else
{
}
}
}
catch
{
Close(true);
}
}
Close:
public void Close(bool causedByError)
{
lock (connectionAccess)
{
if (clientStream != null)
clientStream.Close();
if (client != null)
client.Close();
incomingMailbox.Clear();
outgoingMailbox.Clear();
State = causedByError ? CommunicationState.CommunicationError : CommunicationState.Disconnected;
}
}