11using System ;
2- using System . IO ;
32using System . Net . Security ;
43using System . Net . Sockets ;
54using System . Text ;
@@ -12,7 +11,7 @@ namespace NetCoreServer
1211 /// SSL session is used to read and write data from the connected SSL client
1312 /// </summary>
1413 /// <remarks>Thread-safe</remarks>
15- public class SslSession
14+ public class SslSession : IDisposable
1615 {
1716 /// <summary>
1817 /// Initialize the session with a given server
@@ -125,6 +124,9 @@ internal void Connect(Socket socket)
125124 {
126125 Socket = socket ;
127126
127+ // Update the session socket disposed flag
128+ IsSocketDisposed = false ;
129+
128130 // Setup buffers
129131 _receiveBuffer = new Buffer ( ) ;
130132 _sendBufferMain = new Buffer ( ) ;
@@ -213,6 +215,9 @@ public virtual bool Disconnect()
213215
214216 // Dispose the session socket
215217 Socket . Dispose ( ) ;
218+
219+ // Update the session socket disposed flag
220+ IsSocketDisposed = true ;
216221 }
217222 catch ( ObjectDisposedException ) { }
218223
@@ -751,5 +756,64 @@ private void SendError(SocketError error)
751756 }
752757
753758 #endregion
759+
760+ #region IDisposable implementation
761+
762+ /// <summary>
763+ /// Disposed flag
764+ /// </summary>
765+ public bool IsDisposed { get ; private set ; }
766+
767+ /// <summary>
768+ /// Session socket disposed flag
769+ /// </summary>
770+ public bool IsSocketDisposed { get ; private set ; } = true ;
771+
772+ // Implement IDisposable.
773+ public void Dispose ( )
774+ {
775+ Dispose ( true ) ;
776+ GC . SuppressFinalize ( this ) ;
777+ }
778+
779+ protected virtual void Dispose ( bool disposingManagedResources )
780+ {
781+ // The idea here is that Dispose(Boolean) knows whether it is
782+ // being called to do explicit cleanup (the Boolean is true)
783+ // versus being called due to a garbage collection (the Boolean
784+ // is false). This distinction is useful because, when being
785+ // disposed explicitly, the Dispose(Boolean) method can safely
786+ // execute code using reference type fields that refer to other
787+ // objects knowing for sure that these other objects have not been
788+ // finalized or disposed of yet. When the Boolean is false,
789+ // the Dispose(Boolean) method should not execute code that
790+ // refer to reference type fields because those objects may
791+ // have already been finalized."
792+
793+ if ( ! IsDisposed )
794+ {
795+ if ( disposingManagedResources )
796+ {
797+ // Dispose managed resources here...
798+ Disconnect ( ) ;
799+ }
800+
801+ // Dispose unmanaged resources here...
802+
803+ // Set large fields to null here...
804+
805+ // Mark as disposed.
806+ IsDisposed = true ;
807+ }
808+ }
809+
810+ // Use C# destructor syntax for finalization code.
811+ ~ SslSession ( )
812+ {
813+ // Simply call Dispose(false).
814+ Dispose ( false ) ;
815+ }
816+
817+ #endregion
754818 }
755819}
0 commit comments