WPF,后台工作者和垃圾收集

时间:2013-01-18 02:25:55

标签: c# wpf garbage-collection backgroundworker

考虑以下示例

  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,而不需要后台工作者,但我对这种特定情况感到好奇。)

1 个答案:

答案 0 :(得分:2)

这取决于你的背景工作者为何公开。但是如果你的ViewModel类是唯一一个持有对后台worker的强引用的类,并且后台worker持有一个对viewmodel的硬引用(通过两个事件),那么一旦视图模型不是这两个类,它们都会被标记为垃圾回收暂且不提。

类似question,有更多细节。