// This class shows how to use a disposable resource.
// The resource is first initialized and passed
// The constructor, But it coshould also be
// Initialized in the constructor.
// The lifetime of the resource does not
// Exceed the lifetime of this instance.
// This type does not need a finalizer because it does not
// Directly create a native resource like a file handle
// Or memory in the unmanaged heap.
// The stream passed to the constructor
// Must be readable and not null.
Public Disposableresource (Stream)
{
If (Stream = Null )
Throw New Argumentnullexception ( " Stream in null. " );
If ( ! Stream. Canread)
Throw New Argumentexception ( " Stream must be readable. " );
_ Resource = Stream;
_ Disposed = False ;
}
// Demonstrates using the resource.
// It must not be already disposed.
Public Void Dosomethingwithresource () {
If (_ Disposed)
Throw New Objectdisposedexception ( " Resource was disposed. " );
// Show the number of bytes.
Int Numbytes = ( Int ) _ Resource. length;
Console. writeline ( " Number of bytes: {0} " , Numbytes. tostring ());
}
Public Void Dispose () // Implement Interface
{
Dispose (True);
//Use supressfinalize in case a subclass
//Of this type implements a finalizer.
GC. suppressfinalize (This);
}
Protected Virtual Void Dispose ( Bool Disposing)
{
// If you need thread safety, use a lock around these
// Operations, as well as in your methods that use the resource.
If ( ! _ Disposed)
{
If (Disposing) {
If (_ Resource ! = Null ) // _ Resourec! = NULL, _ Resoure. Dispose (); _ Resoure = NULL
_ Resource. Dispose ();
Console. writeline ( " Object disposed. " );
}
// Indicate that the instance has been disposed.
_ Resource = Null ;
_ Disposed = True ;
}
}
}
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.