This works, if your event is of type EventHandler<EventArgs>
for example. It creates a wrapper for your event handler that is throttled:
private EventHandler<EventArgs> CreateThrottledEventHandler(
EventHandler<EventArgs> handler,
TimeSpan throttle)
{
bool throttling = false;
return (s,e) =>
{
if(throttling) return;
handler(s,e);
throttling = true;
Task.Delay(throttle).ContinueWith(_ => throttling = false);
};
}
Attach like this:
this.SomeEvent += CreateThrottledEventHandler(
(s,e) => Console.WriteLine("I am throttled!"),
TimeSpan.FromSeconds(5));
Although, you should store the handler returned from CreateThrottledEventHandler
if you need to unwire it with -=
later.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…