gpt4 book ai didi

c# - 对有关我的超时类的反馈感兴趣

转载 作者:行者123 更新时间:2023-11-30 15:45:42 25 4
gpt4 key购买 nike

我正在处理的项目中的许多区域都有一个简单的超时检查,它基本上通过一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com