0

考虑以下示例

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

4

1 回答 1

2

这在一定程度上取决于您的后台工作人员为何是公开的。但是,如果您的 ViewModel 类是唯一持有对后台工作人员的强引用的类,并且后台工作人员持有对视图模型的硬引用(通过两个事件),那么一旦视图模型不是,两者都将被标记为垃圾回收不再有任何参考。

类似的问题有更多细节。

于 2013-01-18T02:30:26.950 回答