本文整理汇总了C#中System.WeakReference.GetTarget方法的典型用法代码示例。如果您正苦于以下问题:C# WeakReference.GetTarget方法的具体用法?C# WeakReference.GetTarget怎么用?C# WeakReference.GetTarget使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.WeakReference
的用法示例。
在下文中一共展示了WeakReference.GetTarget方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: IsTrackingContext
private static bool IsTrackingContext(WeakReference<IGraphContext> weakContext)
{
var context = weakContext.GetTarget();
return context != null && !context.CancelToken.IsCancellationRequested;
}
示例2: Test_MemoryLeak_WeakEvent
public void Test_MemoryLeak_WeakEvent()
{
// 1. Normal Event will hold the strong reference which prevent the GC collect.
var view = new TestView();
var viewModel = new TestViewModel();
var reference = new WeakReference(view);
viewModel.TestViewModelEvent += view.OnEventOccured;
viewModel.RaiseTestViewModelEvent();
Assert.AreEqual(1, view.EventCount);
Assert.AreEqual(1, viewModel.GetTestViewModelEventInvocationCount());
view = null;
GC.Collect();
Assert.IsTrue(reference.IsAlive); // Still live
viewModel.TestViewModelEvent -= reference.GetTarget<TestView>().OnEventOccured;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.IsFalse(reference.IsAlive);
reference = null;
Assert.IsNull(reference.GetTarget<TestView>());
// 2. WeakEvent hold the weak reference which will not prevent GC collect.
var view2 = new TestView();
var viewModel2 = new TestViewModel();
var reference2 = new WeakReference(view2);
var weakEvent = new WeakEvent(view2);
weakEvent.AttachEvent(viewModel2, null, "TestViewModelEvent", "OnEventOccured");
viewModel2.RaiseTestViewModelEvent();
Assert.AreEqual(1, view2.EventCount);
view2 = null;
GC.Collect();
Assert.IsFalse(reference2.IsAlive);
viewModel2.RaiseTestViewModelEvent();
Assert.AreEqual(0, viewModel2.GetTestViewModelEventInvocationCount());
}