Borvik / Winsock.Net

Winsock component for .NET networking projects to help make socket communication easier.
MIT License
5 stars 2 forks source link

Error in AsyncSockets.cs #13

Closed mdowdyahoo closed 2 years ago

mdowdyahoo commented 2 years ago

I am opening a connection to server and that works ok. When I close it, I get an error here:

public bool IsConnected { get { try { return internalSocket != null && !(internalSocket.Poll(-1, SelectMode.SelectRead) && internalSocket.Available == 0); } catch (ObjectDisposedException) { return false; } } }

System.ObjectDisposedException occurred HResult=-2146232798 Message=Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'. ObjectName=System.Net.Sockets.Socket Source=System StackTrace: at System.Net.Sockets.Socket.get_Available() InnerException:

Borvik commented 2 years ago

So... I've haven't really touched C# or any .NET language in over 5 years, but based on the code you supplied I think I remember what I was doing in this piece of code.

Let me start the analysis by saying, I don't remember when/if exception logs can be filtered - some might have the logs be more aggressive and want all exception (including handled ones to be logged), and I don't know what your settings are.

public bool IsConnected
{
  get
  {
    try
    {
      return internalSocket != null && !(internalSocket.Poll(-1, SelectMode.SelectRead) && internalSocket.Available == 0);
    }
    catch (ObjectDisposedException) { return false; } // The key line!!!
  }
}

Notice the commented line The key line!!! above. I actually expect the above to throw and ObjectDisposedException - it's unavoidable at times when dealing with the sockets. What I do here those is prevent a simple access to the property IsConnected from blowing up the application, when all someone wanted was to check if the connection was established or not (simple boolean) without the other developers needing to catch the disposed exception.

Here we catch the error and ignore it - it's disposed, we aren't connected and return true.

From available information, I believe this is working as intended.