我正在处理的项目中的许多区域都有一个简单的超时检查,它基本上通过一个 try 循环运行代码,直到它成功或经过 10 秒。
class Timeout {
private readonly DateTime timeoutDate;
public bool FlagSuccess;
public Timeout() {
timeoutDate = DateTime.UtcNow.AddSeconds(10);
flagSuccess = false;
}
public bool continueRunning() {
if (!flagSuccess && DateTime.UtcNow < timeoutDate) return true;
else return false;
}
}
下面是一个正在使用的类的例子:
Timeout t = new Timeout();
while (t.continueRunning()) {
try {
//PUT CODE HERE
t.flagSuccess = true;
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
}
在我实现这个之前,有没有更好更标准的方法来做到这一点?我上面的内容是基于我的盲目直觉。
最佳答案
使用 .NETs Timer
类:
using System.Timers;
public static void Main() {
Timer t = new Timer();
t.Elapsed += new ElapsedEventHandler(ActionWhenFinished);
t.Interval = 10000;
t.Start();
}
public static void ActionWhenFinished()
{
// cancel any action
}
您的 Timeout
类将阻塞它正在运行的当前线程,而 System.Timer
则不是这种情况。
关于c# - 对有关我的超时类的反馈感兴趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4937672/