Created
December 15, 2015 06:56
-
-
Save battleguard/3ae2822ef8978fd8e1f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading; | |
| namespace ConsoleApplication2 | |
| { | |
| class Program | |
| { | |
| public static void Main() | |
| { | |
| var action = new Action( MethodA).Timed(TimeSpan.FromSeconds(7)); | |
| action.Invoke(); // called | |
| Thread.Sleep( 5000 ); | |
| action.Invoke(); // not called | |
| Thread.Sleep( 5000 ); | |
| action.Invoke(); // called | |
| } | |
| public static void MethodA() | |
| { | |
| Console.WriteLine( "Method A Invoked" ); | |
| } | |
| } | |
| public static class ActionExtension | |
| { | |
| public static Action Timed( this Action action, TimeSpan interval ) | |
| { | |
| DateTime lastCalled = DateTime.MinValue; | |
| return () => | |
| { | |
| if ( DateTime.Now - lastCalled < interval ) | |
| return; | |
| action.Invoke(); | |
| lastCalled = DateTime.Now; | |
| }; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment