I have calculations I'm performing which I need to timeout if it runs too long. I might set a timeout of 5 seconds, and do periodic polls throughout my code. Actual code is much more complex, and has heavy recursion and is spread over many classes, but this should give a general idea of how it works. Basically any time something calls recursion or performs something that might take time, it calls AssertTimeout().
private DateTime endTime;
public void PerpareTimeout(int timeoutMilliseconds)
{
endTime = DateTime.UtcNow.AddMilliseconds(timeoutMilliseconds);
}
public void AssertTimeout()
{
if (DateTime.UtcNow > endTime)
throw new TimeoutException();
}
public void DoWork1()
{
foreach (var item in workItems)
{
AssertTimeout();
DoWork2(item)
}
}
public void DoWork2(WorkItem item)
{
foreach (var item in workItems)
{
AssertTimeout();
// ...
}
}
So the problem comes in when I have a debugger attached and I pause execution. I want to somehow disable the timeout for the amount of time paused. So if it runs for 2 seconds, I hit a breakpoint and wait 5 minutes, and then resume, it will run 3 more seconds after resuming execution before timing out.
I could use something like this:
public void PrepareTimeout(int timeoutMilliseconds)
{
if (System.Diagnostics.Debugger.IsDebuggerAttached)
endTime = DateTime.MaxValue;
else
endTime = DateTime.UtcNow.AddMilliseconds(timeoutMilliseconds);
}
But that's basically giving an infinite timeout whenever the program is running in a debug environment, and I want it to time out normally if I don't pause it.
Is there any way to measure time elapsed without counting the time spent paused by the debugger?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…