// Unmanaged Resources
Class unmanagedobject
{
// Simulate unmanaged operations
Public void dounmanagedwork ()
{
Console. writeline ("Do unmanaged work now ...");
}
// Customize the release of an unmanaged operation
Public void docleanup ()
{
Console. writeline ("cleanup unmanaged resource now ...");
}
}
// Managed Resource packaging object
Class unmanagedwrapper: idisposable
{
Protected arraylist _ notifies;
Public Delegate void docleanupdelegate ();
Public unmanagedwrapper ()
{
_ Notifies = new arraylist ();
}
// Register an unmanaged Resource
Public void registerfinalizenotify (docleanupdelegate method)
{
If (! _ Notifies. Contains (method ))
_ Notifies. Add (method );
}
// Deregister an unmanaged Resource
Public void unregisterfinallizenotify (docleanupdelegate method)
{
_ Notifies. Remove (method );
}
// Dispatch reminder message
Protected void callnotifies ()
{
Foreach (Object o in _ notifies)
{
(Docleanupdelegate) O). dynamicinvoke (null );
}
}
// Idisposable Member
Public void dispose ()
{
Callnotifies ();
}
}
Class Application
{
[Stathread]
Static void main (string [] ARGs)
{
Unmanagedwrapper W = new unmanagedwrapper ();
Unmanagedobject obj1 = new unmanagedobject ();
W. registerfinalizenoegate (New unmanagedwrapper. docleanupdelegate (obj1.docleanup ));
Obj1.dounmanagedwork ();
Unmanagedobject obj2 = new unmanagedobject ();
W. registerfinalizenoegate (New unmanagedwrapper. docleanupdelegate (obj2.docleanup ));
Obj2.dounmanagedwork ();
W. Dispose ();
Console. Read ();
}
}
// Output results