title: error: a SafeHandle or CriticalHandle of type ZLibStreamHandle failed to properly release
body: <p>I haven't worked much with streams, so I assume there's a coding error here on my part, somewhere.</p>
  
  <pre><code>   public static SqlBytes Compress(SqlBytes input)
      {
          byte[] data = (byte[])input.Value;
          using (MemoryStream memstream = new MemoryStream(data))
          {
  
              using (GZipStream zipped = new GZipStream(memstream, CompressionMode.Compress))
              {
                  using (MemoryStream output = new MemoryStream()) 
                  {
                      zipped.CopyTo(output);
                      return new SqlBytes(output.ToArray());
                  }
  
              }
  
          }
      }
  </code></pre>
  
  <p>Here's the error in SQL Server 2012 CLR:</p>
  
  <pre><code>Msg 10323, Level 16, State 49, Line 1
  Invalid user code has been identified by .Net Framework Managed Debug Assistant 'releaseHandleFailed':
  A SafeHandle or CriticalHandle of type 'ZLibStreamHandle' failed to properly release the handle with value 0x0000000000000000. This usually indicates that the handle was released incorrectly via another means (such as extracting the handle using DangerousGetHandle and closing it directly or building another SafeHandle around it.)
     at System.Runtime.InteropServices.SafeHandle.InternalDispose()
     at System.IO.Compression.DeflaterZLib.Dispose(Boolean disposing)
     at System.IO.Compression.DeflateStream.Dispose(Boolean disposing)
     at System.IO.Stream.Close()
     at System.IO.Compression.GZipStream.Dispose(Boolean disposing)
     at System.IO.Stream.Close()
     at UserDefinedFunctions.Compress(SqlBytes input)
     at SQLCLR_Eval(IntPtr , IntPtr , IntPtr )
  </code></pre>