2015-05-07 55 views
0

当我打开Cellule.cs类时,会创建一个计时器,当Cellule.cs关闭时,计时器仍会调用表单。计时器不会收集垃圾

我该如何有效地处置它。这会导致一个问题,因为表单Cellules.Cs经常打开,并且每次调用TimeHasChanged()都会对数据库进行一次调用;

我已经尝试在Btimer中添加一个Dispose()方法并将计时器设置为null,但它不能解决问题。

private BTimer timer; 

public Cellules() 
{ 
    timer = new BTimer(30000); 
    timer.TheTimeChanged += TimeHasChanged; 
} 

    protected void TimeHasChanged() 
    { 
     controller.UpdateTimeMesPieces(); 
     lblTime.Text = controller.UpdateTimeClock(); 
    } 

而且继承人的计时器

public class BTimer 
{ 
    private string theTime; 
    private Timer timer; 

    public BTimer(int interval) 
    { 
     timer = new Timer(); 
     timer.Tick += new EventHandler(Timer_Tick); 
     timer.Interval = interval; 
     timer.Start(); 
    } 

    public delegate void TimerTickHandler(); 

    public event TimerTickHandler TheTimeChanged; 

    public string TheTime 
    { 
     get 
     { 
      return theTime; 
     } 
     set 
     { 
      theTime = value; 
      OnTheTimeChanged(); 

     } 
    } 

    protected void OnTheTimeChanged() 
    { 
     if (TheTimeChanged != null) 
     { 
      TheTimeChanged(); 
     } 
    } 

    private void Timer_Tick(object sender, EventArgs e) 
    { 
     TheTime = "Bing"; 
    } 
} 
+0

代码不能编译:'BTimer'没有实现' IDisposable' – Blorgbeard

+0

@Blorgbeard对不起,我删除它,这是从我最后一次尝试解决它 – Insecurefarm

回答

1

如果一个类包含一个成员是一次性该类应该实现IDisposable以及

注:BTimer需要实现IDisposable。

class Cellules : IDisposable 
{ 
    BTimer timer // disposable member 

    public void Dispose() // implementing IDisposable 
    { 
     timer.Dispose(); 
    } 

} 

然后当然,当你调用来完成响应处置上Cellules

的任何实例您的编辑

要实现对BTimer类的IDisposable的

public class BTimer : IDisposable 
{ 
private string theTime; 
private Timer timer; 

........  

void Dispose() 
{ 
    timer.Stop(); 
    timer.Dispose(); 

} 

}

我会添加的是一个停止方法的BTimer,所以你不需要处置停止计时器。

+0

这是从我最后一次尝试解决它,我编辑后发表遗憾 – Insecurefarm

0

您的BTimer尚未实现IDisposable,您必须注销您的TheTimeChanged事件后,您不再需要它。

2

需要实现IDisposable,并在Dispose方法,你需要Dispose定时器,而不是仅仅将其设置为空`。

你或许应该撇清任何事件形成的计时器以及(尽管这可能是不必要的,如果计时器的Dispose方法做到这一点):

timer.Tick -= Timer_Tick; 
timer.Dispose();