Hilfklasse, um auf Ereignisse zeitverzögert reagieren zu können. Vergleichbar mit einer Entprellung von elektrischen Signalen.
Beispiel anhand dem SelectedIndexChanged Ereignisses einer Combobox:
this.cmb_Test = new ComboBox();
this.cmb_Test.SelectedIndexChanged += new DelayedEventHandler(5000, new EventHandler(this.egC_GlassCombobox1_SelectedIndexChanged)).OnDelay;
/// <summary>
/// Helper class to call a function delayed
/// </summary>
public class DelayedEventHandler
{
/// <summary>
/// Delay-Timer
/// </summary>
private Timer t_Delay = new Timer();
/// <summary>
/// Delegate that should be invoked after delay
/// </summary>
private EventHandler eventDelegate;
/// <summary>
/// Delegate that receive the outer event to start delay
/// </summary>
public EventHandler OnDelay;
/// <summary>
/// The sender which raised the outer event
/// </summary>
private object sender;
/// <summary>
/// The event args that comes from the outer event
/// </summary>
private EventArgs e;
/// <summary>
/// Inits the delayed eventhandler
/// </summary>
/// <param name="delay">the time to wait before event is raised in ms</param>
/// <param name="eventDelegate">the delegate that should be invoked after delay</param>
public DelayedEventHandler(int delay, EventHandler eventDelegate)
{
t_Delay.Interval = delay;
t_Delay.Tick += new EventHandler(t_Delay_Tick);
this.eventDelegate = eventDelegate;
//bind delegate to register function, that start delay timer
this.OnDelay = new EventHandler(this.Register);
}
/// <summary>
/// The time to wait before event is raised in ms
/// </summary>
public int Delay
{
get { return this.t_Delay.Interval; }
set { this.t_Delay.Interval = value; }
}
private bool stopAndRestart = true;
/// <summary>
/// Controls the delay behaviour
/// </summary>
public bool StopAndRestart
{
get { return stopAndRestart; }
set { stopAndRestart = value; }
}
/// <summary>
/// method invoked after delay
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void t_Delay_Tick(object sender, EventArgs e)
{
//stop timer
this.t_Delay.Stop();
//invoke outer function by delegate with right sender and eventargs
if (this.eventDelegate != null)
this.eventDelegate(this.sender, this.e);
}
/// <summary>
/// invoked when outer event is raised
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Register(object sender, EventArgs e)
{
this.sender = sender;
this.e = e;
if (this.StopAndRestart)
{
//stop and restart timer
this.t_Delay.Stop();
}
this.t_Delay.Start();
}
8 Kommentare zum Snippet