Use register/notify mode to implement unified disposal of unmanaged resources in C #

Source: Internet
Author: User

// 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.