تقييم الموضوع :
  • 0 أصوات - بمعدل 0
  • 1
  • 2
  • 3
  • 4
  • 5
موضوع للنقاش- الواجهة IDisposable
#2
كاتب المشاركة : samerselo

المثال الأول

في مكتبة MSDN وجدت هذا المثال حول تحقيق الواجهة IDisposable

كود :
Public Class DisposableResource
Implements IDisposable

Private _resource As Stream

Private _disposed As Boolean

' The stream passed to the constructor
' must be readable and not null.
Public Sub New(ByVal stream As Stream)
MyBase.New()
If (stream Is Nothing) Then
Throw New ArgumentNullException("Stream is null.")
End If
If Not stream.CanRead Then
Throw New ArgumentException("Stream must be readable.")
End If
_resource = stream
Dim objTypeName As String = _resource.GetType.ToString
_disposed = False
End Sub

' Demonstrates using the resource.
' It must not be already disposed.
Public Sub DoSomethingWithResource()
If _disposed Then
Throw New ObjectDisposedException("Resource was disposed.")
End If

' Show the number of bytes.
Dim numBytes As Integer = CType(_resource.Length, Integer)
Console.WriteLine("Number of bytes: {0}", numBytes.ToString)
End Sub

Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)

' Use SupressFinalize in case a subclass
' of this type implements a finalizer.
GC.SuppressFinalize(Me)
End Sub

Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If Not _disposed Then

' If you need thread safety, use a lock around these
' operations, as well as in your methods that use the resource.
If disposing Then
If (Not (_resource) Is Nothing) Then
_resource.Dispose()
End If
Console.WriteLine("Object disposed.")
End If

' Indicates that the instance has been disposed.
_resource = Nothing
_disposed = True
End If
End Sub
End Class
لاحظ أن stream هو مصادر مدارة ( راجع ما تحدثنا عنه سابقا ) لهذا قمنا باستدعاء الوظيفة Dispose الخاصة به ضمن الوظيفة Dispose في فئتنا داخل حلقة If ( مكان كود تحرير المصادر المدارة )
}}}
تم الشكر بواسطة:


الردود في هذا الموضوع
موضوع للنقاش- الواجهة IDisposable - بواسطة Raggi Tech - 05-10-12, 01:20 AM


التنقل السريع :


يقوم بقرائة الموضوع: