一般来说,垃圾收集是一种很好的做法,因为它可以释放资源。如何在以下代码的keepingTime
方法中实现正确的垃圾回收?或者,事实上,我什至需要?!
System.Timers.Timer
允许 IDisposable 接口,所以 'using' 是一个选项,但不是在下面,因为计时器的范围需要扩展到myTimer_Elapsed
订阅 Timer Elapsed 事件的方法。我已经进行了两次垃圾收集尝试,但都失败了,因为计时器没有停留足够长的时间!
由于其他原因,我之前在HERE中讨论过此代码
public partial class AirportParking : Form
{
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//instance variables of the form
System.Timers.Timer myTimer;
private const string EvenText = "hello";
private const string OddText = "hello world";
static int tickLength = 100;
static int elapsedCounter;
private int MaxTime = 5000;
private TimeSpan elapsedTime;
private readonly DateTime startTime = DateTime.Now;
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public AirportParking()
{
InitializeComponent();
lblValue.Text = EvenText;
keepingTime();
}
//method for keeping time
public void keepingTime() {
myTimer = new System.Timers.Timer(tickLength);
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
myTimer.AutoReset = true;
myTimer.Enabled = true;
myTimer.Start();
//ATTEMPT_1.tried the following unsuccessfully
//using (System.Timers.Timer myTimer = new System.Timers.Timer(tickLength))
//{
// myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
// myTimer.AutoReset = true;
// myTimer.Enabled = true;
// myTimer.Start();
//}
//ATTEMPT_2.tried the following unsuccessfully
//myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
//myTimer.AutoReset = true;
//myTimer.Enabled = true;
//try
//{
// myTimer.Start();
//}
//finally
//{
// myTimer.Dispose();
//}
}
private void myTimer_Elapsed(Object myObject,EventArgs myEventArgs){
elapsedCounter++;
elapsedTime = DateTime.Now.Subtract(startTime);
if (elapsedTime.TotalMilliseconds < MaxTime)
{
this.BeginInvoke(new MethodInvoker(delegate
{
this.lblElapsedTime.Text = elapsedTime.ToString();
if (elapsedCounter % 2 == 0)
this.lblValue.Text = EvenText;
else
this.lblValue.Text = OddText;
}));
}
else {myTimer.Stop();}
}
}