考虑以下示例
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,而不需要后台工作人员,但我对这个特定场景很好奇。)