@@ -13,6 +13,7 @@ public unsafe class MemoryMappedStream : Stream
1313 private readonly long length ;
1414 private long position ;
1515 private byte * ptr ;
16+ private bool disposed ;
1617
1718 /// <summary>
1819 /// Initializes a new instance of the <see cref="MemoryMappedStream"/> class.
@@ -57,6 +58,11 @@ public override void Flush()
5758 /// <inheritdoc/>
5859 public override int Read ( byte [ ] buffer , int offset , int count )
5960 {
61+ if ( this . disposed )
62+ {
63+ throw new ObjectDisposedException ( nameof ( MemoryMappedStream ) ) ;
64+ }
65+
6066 int read = ( int ) Math . Min ( count , this . length - this . position ) ;
6167
6268 new Span < byte > ( this . ptr + this . position , read )
@@ -70,6 +76,11 @@ public override int Read(byte[] buffer, int offset, int count)
7076 /// <inheritdoc/>
7177 public override int Read ( Span < byte > buffer )
7278 {
79+ if ( this . disposed )
80+ {
81+ throw new ObjectDisposedException ( nameof ( MemoryMappedStream ) ) ;
82+ }
83+
7384 int read = ( int ) Math . Min ( buffer . Length , this . length - this . position ) ;
7485
7586 new Span < byte > ( this . ptr + this . position , read )
@@ -83,6 +94,11 @@ public override int Read(Span<byte> buffer)
8394 /// <inheritdoc/>
8495 public override long Seek ( long offset , SeekOrigin origin )
8596 {
97+ if ( this . disposed )
98+ {
99+ throw new ObjectDisposedException ( nameof ( MemoryMappedStream ) ) ;
100+ }
101+
86102 long newPosition = this . position ;
87103
88104 switch ( origin )
@@ -124,5 +140,12 @@ public override void Write(byte[] buffer, int offset, int count)
124140 {
125141 throw new NotSupportedException ( ) ;
126142 }
143+
144+ /// <inheritdoc/>
145+ protected override void Dispose ( bool disposing )
146+ {
147+ this . accessor . SafeMemoryMappedViewHandle . ReleasePointer ( ) ;
148+ this . disposed = true ;
149+ }
127150 }
128151}
0 commit comments