0
請看下面的例子WPF,背景工人和垃圾收集
public class ChildViewModel
{
public BackgroundWorker BackgroundWorker;
public ChildViewModel()
{
InitializeBackgroundWorker();
BackgroundWorker.RunWorkerAsync();
}
private void InitializeBackgroundWorker()
{
BackgroundWorker = new BackgroundWorker();
BackgroundWorker.DoWork += backgroundWorker_DoWork;
BackgroundWorker.RunWorkerCompleted +=backgroundWorker_RunWorkerCompleted;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do something
}
void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//do time consuming task
Thread.Sleep(5000);
}
public void UnregisterEventHandlers()
{
BackgroundWorker.DoWork -= backgroundWorker_DoWork;
BackgroundWorker.RunWorkerCompleted -= backgroundWorker_RunWorkerCompleted;
}
}
public class ParentViewModel
{
ChildViewModel childViewModel;
public ParentViewModel()
{
childViewModel = new ChildViewModel();
Thread.Sleep(10000);
childViewModel = null;
//would the childViewModel now be eligible for garbage collection at this point or would I need to unregister the background worker event handlers by calling UnregisterEventHandlers?
}
}
問:我是否需要註銷的背景工人的事件處理程序childViewModel對象符合垃圾收集。 (這只是一個例子,我知道我可以在這種情況下使用TPL,而不需要後臺工作人員,但我很好奇這個特定場景。)
我的錯誤,我公開能夠註銷處理程序,但只是爲此目的添加了公共方法。根據你的回答,我明白即使這不是必要的。感謝您鏈接到另一個問題btw – nighthawk457