Created
October 25, 2011 21:54
-
-
Save stuartcarnie/1314463 to your computer and use it in GitHub Desktop.
Example of non-determinism of finalizers. This will crash with ObjectDisposedException on v4.0 x64 and x86 runtimes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace FinalizerTest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
for (var i = 0; i < 10000; i++) | |
{ | |
var parent = new MyClass(new MyClass()); | |
} | |
} | |
} | |
public class MyClass : IDisposable | |
{ | |
private MyClass _other; | |
private bool _disposed; | |
public MyClass(MyClass other) | |
{ | |
_other = other; | |
// generate some additional memory to move objects through different generations | |
var a = new byte[49152]; | |
} | |
public MyClass() | |
{ | |
} | |
public MyClass Other | |
{ | |
get { return _other; } | |
set { _other = value; } | |
} | |
~MyClass() | |
{ | |
Dispose(false); | |
} | |
public void Dispose() | |
{ | |
this.Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
private void Dispose(bool disposing) | |
{ | |
if (_disposed) | |
throw new ObjectDisposedException("MyClass"); | |
if (_other != null) | |
_other.Dispose(); | |
_disposed = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment