Created
February 27, 2013 22:19
-
-
Save einarwh/5052353 to your computer and use it in GitHub Desktop.
Controlling time using using.
This file contains 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
class Program | |
{ | |
static void Main() | |
{ | |
Tick(); Tick(); Tick(); | |
DateTime dt = DateTime.Now; | |
using (Timepiece.Replacement(() => dt.Add(dt - DateTime.Now))) | |
{ | |
Tick(); Tick(); Tick(); | |
} | |
Tick(); Tick(); Tick(); | |
} | |
static void Tick() | |
{ | |
Thread.Sleep(1000); | |
Console.WriteLine("The time is {0}", Timepiece.Now.ToLongTimeString()); | |
} | |
} | |
public static class Timepiece | |
{ | |
private static Func<DateTime> _ = () => DateTime.Now; | |
public static DateTime Now { get { return _(); } } | |
public static IDisposable Replacement(Func<DateTime> f) | |
{ | |
return new TempTimepiece(f); | |
} | |
class TempTimepiece : IDisposable | |
{ | |
private readonly Func<DateTime> _original; | |
public TempTimepiece(Func<DateTime> f) | |
{ | |
_original = _; | |
_ = f; | |
} | |
public void Dispose() | |
{ | |
_ = _original; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment