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

标签 c# class timer timeout

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

相关文章:

java - Pong 游戏运行速度太快,且带有 FPS 计数器

c# - 使用 AJAX 调用 jQuery 传送文件

c# - 使用响应式扩展观察标准输出

javascript - 使用 onClick 通过 javascript 更改类

swift - 扫描 BLE 设备并将它们呈现在 UITableView 中

ruby - 如何在 Ruby 中实现私有(private)内部类

Java时钟同步

c - 在 C 中初始化定时器

c# - 需要协助 : write a small program that will turn on the computer and executes a specified program.

c# - 如何将值关联到函数调用?