代码之家  ›  专栏  ›  技术社区  ›  Dai

如何实现一个DateTime.UtcNow来考虑调试器暂停?

  •  0
  • Dai  · 技术社区  · 6 年前

    考虑:

    public static void Main()
    {
        DateTime now = DateTime.UtcNow;
        String x = Console.ReadLine(); // <-- breakpoint on this line
        DateTime then = DateTime.UtcNow;
    }
    

    如果我在调试器中运行此程序,并且在 Console.ReadLine() 调用并让调试器在手动恢复之前暂停程序30秒,然后 then 价值将是 now + 30s . 这可能会影响调试计时相关的错误,使用调试器可能无法检测到这些错误,因为程序暂停的时间仍添加到 DateTime.Utc 因为它代表挂钟时间。

    我想知道 DateTime.UtcNow 好像程序没有暂停30秒,那样我就可以抽象出来 日期时间.UtcNow . 例如,如果 System.Diagnostics.Debugger 具有以下功能:

    using System.Diagnostics;
    
    private static DateTime _lastPaused      = DateTime.UtcNow;
    private static TimeSpan _pauseAdjustment = TimeSpan.Zero;
    
    public static void Main()
    {
        Debugger.OnPause => { _lastPaused = DateTime.UtcNow; };
        Debugger.OnResume => { _pauseAdjustment += DateTime.UtcNow - _lastPaused;  };
    
        DateTime now = GetDebuggerUtcNow();
        String x = Console.ReadLine(); // <-- breakpoint on this line
        DateTime then = GetDebuggerUtcNow();
    }
    
    private static DateTime GetDebuggerUtcNow()
    {
        return DateTime.UtcNow - _pauseAdjustment;
    }
    

    这与获取“cpu时间”不同,因为此值不一定与运行它所花费的cpu周期或指令数有关,例如,等待异步操作完成所花费的时间。

    但当然, Debugger.OnPause Debugger.OnResume 不存在-还有另一种方法吗?

    0 回复  |  直到 6 年前