Introduction
This idea was thought up by a colleague of mine at work by the name of Greg. It is a wonderful idea that will allow you to defer logic of any algorithm you write.
This can be extremely helpful if you design visual controls and use events to drive your control. Custom drawing algorithms can benefit greatly from this.
Using the Code
Here is the base class that helps drive this...
public class DelayedSingleActionInvoker : DispatcherObject
{
#region Private Properties
private Action ActionToInvoke { get; set; }
private DispatcherOperation LastOperation { get; set; }
private DispatcherPriority Priority { get; set; }
private DispatcherTimer Timer { get; set; }
#endregion
#region Constructors
public DelayedSingleActionInvoker(Action action)
{
ActionToInvoke = action;
Priority = DispatcherPriority.Background;
Timer = new DispatcherTimer(Priority, Dispatcher);
Timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
Timer.Tick += Tick;
}
public DelayedSingleActionInvoker(Action action, TimeSpan waitSpan)
{
ActionToInvoke = action;
Priority = DispatcherPriority.Background;
Timer = new DispatcherTimer(Priority, Dispatcher);
Timer.Interval = waitSpan;
Timer.Tick += Tick;
}
public DelayedSingleActionInvoker(Action action, TimeSpan waitSpan, DispatcherPriority priority)
{
ActionToInvoke = action;
Priority = priority;
Timer = new DispatcherTimer(Priority, Dispatcher);
Timer.Interval = waitSpan;
Timer.Tick += Tick;
}
#endregion
#region Events
private void Tick(object sender, EventArgs e)
{
LastOperation = Dispatcher.BeginInvoke((Action)delegate
{
Timer.Stop();
ActionToInvoke.Invoke();
LastOperation = null;
}, Priority);
}
#endregion
#region Public Methods
public void BeginInvoke()
{
if (Timer.IsEnabled) Timer.Stop();
if (LastOperation != null)
LastOperation.Abort();
Timer.Start();
}
#endregion
}
Here is a perfect example...
public partial class MainWindow : Window
{
private DelayedSingleActionInvoker SizeChangedInvoker { get; set; }
public MainWindow()
{
InitializeComponent();
SizeChanged += Window_SizeChanged;
SizeChangedInvoker = new DelayedSingleActionInvoker(SizeChangedLogic);
}
private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
{
SizeChangedInvoker.BeginInvoke();
}
private void SizeChangedLogic()
{
Debug.WriteLine("SizeChanged goodness");
}
}
That is just a WPF application project in Visual Studio.
Run your main window and resize it for a few seconds and watch as the message fires half a second after you stop resizing the window.
Developed various languages over the years. Found C# and fell in love with it. Been doing it ever since. Love WPF or ASP.Net MVC with the Razor view engine as front-end technologies. As a developer I want to make development easier for all developers. I like designing and providing tools for other programmers to use.