开发者

How to change the value of DateTime.UtcNow for a Process or Thread?

Is there a way, even a very sneaky way, to change the time that a DateTime.UtcNow returns for a process or thread?

The SetSystemTime() win32 API call will change the time on the entire system. I've used this before but I would like a method that is less evil to other processes running on the system. Messing with the time is bad kungfoo on automated build servers.

C# seems to lack the language featu开发者_运维问答res required to override the default behavior.

Perhaps the method that .Net uses to obtain the current time could be proxied in some way?


You should wrap the current time in your own proxy class and use that instead, then you're free to return whatever you like.


The DateTime.UtcNow probably calls into Kernel32!GetSystemTimeAsFileTime() or something similar. You could probably use the Detour library from Microsoft Research to hook this API, then in your hook function, detect the process and thread IDs which you'd like to dupe.

Good luck running the software!


Yeah, define interface IKnowCurrentTime with single property UtcNow. Use dependency injection to inject that into your classes. Make default implementation call DateTime.UtcNow and pass that to your classes in PROD. For testing purposes, make a mock of IKnowCurrentTime and have that return whatever. The way of the future baby.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜