Skip to content

Instantly share code, notes, and snippets.

@stuartcarnie
Created October 25, 2011 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartcarnie/1314463 to your computer and use it in GitHub Desktop.
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.
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