05-10-12, 01:25 AM
كاتب المشاركة : Islam Ibrahim
سأحاول فيما يلي إضافة بعض الأمثلة عن كيفية استخدام الفئة WeakReference بشكل عملي في تطبيقاتناهذا مثال بسيط عبارة عن فئة تقوم بحفظ عناصر الصور داخل ال Cache
كود :
Public Class ImageCache
Private _cache As IDictionary(Of String, WeakReference) = New Dictionary(Of String, WeakReference)()
Public Function GetImage(ByVal path As String) As Image
Dim reference As WeakReference
If _cache.TryGetValue(path, reference) Then
If reference.IsAlive Then
Return DirectCast(reference.Target, Image)
Else
' image has been garbage collected
' remove reference from cache
_cache.Remove(path)
End If
End If
' not in cache, so load
Dim image__1 As Image = Image.FromFile(path)
reference = New WeakReference(image__1)
_cache.Add(path, reference)
Return image__1
End Function
End Classكود :
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports System.Xml
Public Class Program
Sub Main(ByVal args As String())
Dim cacheFile As New CacheXmlDocument("UIConfig.xml")
Console.WriteLine(cacheFile.GetXml())
Console.WriteLine(cacheFile.GetXml())
Console.Read()
End Sub
End Class
Public Class CacheXmlDocument
Public ReadOnly FileName As String
Private wrText As WeakReference
Public Sub New(ByVal fileName__1 As String)
FileName = fileName__1
End Sub
Private Function ReadXml() As String
'load the xml document
Dim xmlDoc As New XmlDocument()
xmlDoc.Load(FileName)
Dim xml As String = xmlDoc.InnerXml
'create the weak reference
wrText = New WeakReference(xml)
Return xml
End Function
Public Function GetXml() As String
Dim text As Object = Nothing
'you may also use wrText.IsAlive to check it has been GC'ed
If wrText IsNot Nothing Then
text = wrText.Target
End If
If text IsNot Nothing Then
Return text.ToString()
Else
Return ReadXml()
End If
End Function
End Class