Bug 25850 - SafeHandle.Close() is not idempotent.
Summary: SafeHandle.Close() is not idempotent.
Alias: None
Product: Class Libraries
Classification: Mono
Component: mscorlib (show other bugs)
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:


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

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.

Create a new report for Bug 25850 on Developer Community or GitHub if you have new information to add and do not yet see a matching report.

  • Export the original title and description: Developer Community HTML or GitHub Markdown
  • Copy the title and description into the new report. Adjust them to be up-to-date if needed.
  • Add your new information.

In special cases on GitHub you might also want the comments: GitHub Markdown with public comments

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.

Related Links: