Deterministic Disposable

time to read 1 min | 135 words

Here is a challenge, get this to work:

/// Executes the given handler when the instance is disposed
/// of using the Dispose(instance);
/// Note: Doesn't cause memory leak
public void OnDisposable(object instance, Action<object> action);

/// Executes the previously registered Action for this
/// instance
public void Dispose(object instance);

The key part here is to get this to work without causing a memory leak. Furthermore, assume that you need to handle this scenario as well without causing a leak:

object instance = new object();
OnDisposable(instance, delegate(object obj)
    Console.WriteLine("Disposing of {0}", obj);