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. )