2013-01-18 100 views
0

請看下面的例子WPF,背景工人和垃圾收集

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,而不需要後臺工作人員,但我很好奇這個特定場景。)

回答

2

這取決於你爲什麼背景工作者是公開的。但是,如果您的ViewModel類是唯一持有對後臺工作者的強引用的類,並且後臺工作人員持有對視圖模型的硬引用(通過兩個事件),則一旦視圖模型不是再沒有任何參考。

類似question與一些更多的細節。

+0

我的錯誤,我公開能夠註銷處理程序,但只是爲此目的添加了公共方法。根據你的回答,我明白即使這不是必要的。感謝您鏈接到另一個問題btw – nighthawk457