Here’s a piece of .Net weirdness I wrote recently. I needed to ensure that a method gets called at most once every 5 seconds, and that extraneous calls are ignored. I was surprised that .Net doesn’t have a built-in construct for this sort of thing. Here’s what I came up with. Pretty weird, huh?
private static void MarkupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ThreadPool.QueueUserWorkItem(x =>
{
if (Monitor.TryEnter(updateLock, 0))
{
var fe = (FreeformEditor)d;
fe.Dispatcher.Invoke(new Action(() => UpdatePreview(fe, (string) e.NewValue)));
Thread.Sleep(5000);
Monitor.Exit(updateLock);
}
});
}