Search code examples
c#wpfgarbage-collectionbackgroundworker

WPF, Background worker and garbage collection


Consider the following example

  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?  
    }
}

Question: Do I need to unregister the background workers event handlers for the childViewModel object to be eligible for garbage collection. (This is just an example. I am aware I can use TPL in this situation without the need for a background worker but I am curious about this specific scenario. )


Solution

  • It depends a bit on why your backgroundworker is public. But if your ViewModel class is the only class holding a strong reference to the background worker, and the background worker is holding a hard reference to the viewmodel (via the two events), both will be marked for garbage collection once the view model is not hold by any reference anymore.

    Similar question with some more detail.