Can be called periodically by external threads to ensure cleanup instead of depending upon calls to Add()
Syntax
Visual Basic (Declaration) | |
---|
Public Sub Tick() |
Example
Library/Library.Test/TestObjectKeepAlive.cs
C# | Copy Code |
---|
WeakReference r;
ObjectKeepAlive keep = new ObjectKeepAlive(1, 10, TimeSpan.FromTicks(1), true);
for (int i = 0; i < 35; i++)
keep.Add(i);
if (true)
{
object target = new MyObject();
r = new WeakReference(target);
keep.Add(target);
target = null;
}
_destroyed = false;
Assert.IsTrue(r.IsAlive);
for (int i = 0; i < 100; i++)
keep.Tick();
Assert.IsTrue(r.IsAlive);
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
Assert.IsTrue(r.IsAlive);
Assert.IsFalse(_destroyed);
System.Threading.Thread.Sleep(1);
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
Assert.IsTrue(r.IsAlive);
Assert.IsFalse(_destroyed);
keep.Clear();
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
Assert.IsFalse(r.IsAlive);
Assert.IsTrue(_destroyed); |
VB.NET | Copy Code |
---|
Dim r As WeakReference
Dim keep As New ObjectKeepAlive(1, 10, TimeSpan.FromTicks(1), True)
Dim i As Integer = 0
While i < 35
keep.Add(i)
System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While
If True Then
Dim target As Object = New MyObject()
r = New WeakReference(target)
keep.Add(target)
target = Nothing
End If
_destroyed = False
Assert.IsTrue(r.IsAlive)
Dim i As Integer = 0
While i < 100
keep.Tick()
System.Math.Max(System.Threading.Interlocked.Increment(i),i - 1)
End While
Assert.IsTrue(r.IsAlive)
GC.GetTotalMemory(True)
GC.WaitForPendingFinalizers()
Assert.IsTrue(r.IsAlive)
Assert.IsFalse(_destroyed)
System.Threading.Thread.Sleep(1)
GC.GetTotalMemory(True)
GC.WaitForPendingFinalizers()
Assert.IsTrue(r.IsAlive)
Assert.IsFalse(_destroyed)
keep.Clear()
GC.GetTotalMemory(True)
GC.WaitForPendingFinalizers()
Assert.IsFalse(r.IsAlive)
Assert.IsTrue(_destroyed) |
Requirements
Target Platforms: Windows XP, Windows Server 2003, Windows Vista, Windows Server 2008, Windows 7
See Also