开发者

List<CustomObject>: How Custom Object removes itself from the list?

I created a class that implements a System.Timers.Timer with an elapse event.


private void ElapseEvent(object source, ElapsedEventArgs e){
//read from serial port device
}

In the main program I have a private List<MyTimerClass> _timers.

I dynamically start the timer and add it to the timer list.


 var timer1= new MyTimerClass();
 timer1.Execute("Device A");
_timers.Add(timer1);

 var timer2= new MyTimerClass();
 timer2.Execute开发者_高级运维("Device B");
_timers.Add(timer2);

When the ElapseEvent encounters an error and the serial port was disconnected, I want to remove the timer from the List. How can I possibly do that?


You can add a OnError Method at the class that contains the timers. In order to let the parent class know that an error occurs. Something like the following:

At MyTimerClass

public MyTimerClass(Action<MyTimerClass, Exception> onError)
{
    this.onError = onError;
}

private void ElapseEvent(object source, ElapsedEventArgs e){
try{
//read from serial port device
}
catch(Exception ex) // It would be better if you know the exceptions you want to handle
{
  if(this.onError != null)
  {
   this.onError(this, ex);
  }
}
}

At the parent class:

var timer1= new MyTimerClass(this.OnTimerError);
 timer1.Execute("Device A");
_timers.Add(timer1);

 var timer2= new MyTimerClass(this.OnTimerError);
 timer2.Execute("Device B");
_timers.Add(timer2);



public void OnTimerError(MyTimerClass timer, Exception error)
{
 //Log the exception
  _timers.Remove(timer);
}


If your _timers is a static variable, then create a static event handler in the same class. When the error is thrown in a timer's ElapseEvent, call the event handler with reference to itself, and have the static event handler remove the error'ed timer from the list.


The Observer Pattern. .NET has native support for this.


You should check out the Command Pattern; sounds like it would be perfect for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜