Bug 25850 - SafeHandle.Close() is not idempotent.
Summary: SafeHandle.Close() is not idempotent.
Alias: None
Product: Class Libraries
Classification: Mono
Component: mscorlib ()
Version: master
Hardware: PC Mac OS
: --- normal
Target Milestone: Untriaged
Assignee: Marek Safar
Depends on:
Reported: 2015-01-08 17:55 UTC by Jonathan Pryor
Modified: 2015-01-12 08:05 UTC (History)
2 users (show)

Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description Jonathan Pryor 2015-01-08 17:55:12 UTC
Common practice and design guidelines is that IDisposable.Dispose()/Close()/etc. methods can be called multiple times on a method, and shouldn't throw an ObjectDisposedException.

Mono's SafeHandle implementation doesn't do that:

  using System;
  using System.Runtime.InteropServices;

  class MySafeHandle : SafeHandle {

    public MySafeHandle ()
      : base (IntPtr.Zero, ownsHandle:false)

    protected override bool ReleaseHandle ()
      return true;

    public override bool IsInvalid {
      get {return base.handle == IntPtr.Zero;}

  class App {
    public static void Main ()
      var h = new MySafeHandle ();
      h.Close ();
      h.Close ();

Expected results: what .NET does: no output.

Actual results: an unhandled exception!

> System.ObjectDisposedException: The object was used after being disposed.
>   at System.Runtime.InteropServices.SafeHandle.Close () [0x0008d] in /private/tmp/source-mono-mac-3.12.0-branch-32/bockbuild-mono-3.12.0-branch/profiles/mono-mac-xamarin/build-root/mono-3.12.0/mcs/class/corlib/System.Runtime.InteropServices/SafeHandle.cs:107 
>   at App.Main () [0x0000e] in /Users/jon/tmp/csharp/sh.cs:28
Comment 1 Marek Safar 2015-01-12 08:05:51 UTC
Fixed in master