gpt4 book ai didi

C# 4.0 - 间隔上的线程

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

我正在使用 C# 4.0。我有一段代码,我想每 2-3 分钟执行一次。使用可用的 4.0 线程功能执行此操作的正确方法是什么?

最佳答案

最简单的方法是使用 System.Threading.Timer .要记住的一件事是,无论您的代码在做什么(重新进入),它都会消失。换句话说,如果所需的间隔是 3 分钟,而您执行的代码需要 2 分钟,它将在此代码完成后 1 分钟触发。此外,如果您的代码花费超过 3 分钟,那么它将被并行调用,您将不得不注意线程安全。如果这没问题,并且您不希望您的代码花费很长时间,那么您可以使用以下方法:

Timer _timer = new Timer(DoWork, "someArg", TimeSpan.Zero, TimeSpan.FromSeconds(3));

private void DoWork(object state) {
// this code will get executed every 3 seconds:
String argument = (String) state;
}

但如果您希望您的计时器是连续的(等待代码完成后再开始新的间隔),您将需要在每次 Tick 时重置它。

Timer _timer = new Timer(DoWork, "someArg", TimeSpan.Zero, TimeSpan.FromSeconds(3));

private void DoWork(object state) {
// this code will get executed 3 seconds after the last DoWork finished
String argument = (String)state;


// make sure that timer will get executed in 3 seconds but will not repeat.
// this code guarantees that timer will wait for this code to complete
// before starting new interval.
_timer.Change(TimeSpan.FromSeconds(3), TimeSpan.FromMilliseconds(-1));
}

您还需要确保您的计时器实例在您仍然需要它时不会被垃圾回收。另请注意,.NET 包含 3 个不同的计时器类,但您很可能需要 System.Threading.Timer 而不是 System.Windows.Forms.Timer 而不是 System.计时器。计时器。提供了很好的总结 here

如果您预见到更高级的调度要求(每隔一个星期一运行代码等),那么您可以使用 Quartz.NET .它是一个开源企业作业调度程序,具有许多其他功能并且集成起来相对简单(引用一个 dll)。

关于C# 4.0 - 间隔上的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6966605/

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