C# 每隔几秒重复一次函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11296897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 17:18:04  来源:igfitidea点击:

Repeating a function every few seconds

c#.netloops

提问by

I want to repeat a function from the moment the program opens until it closes every few seconds. What would be the best way to do this in C#?

我想从程序打开的那一刻起重复一个函数,直到它每隔几秒关闭一次。在 C# 中执行此操作的最佳方法是什么?

采纳答案by Kendall Frey

Use a timer. There are 3 basic kinds, each suited for different purposes.

使用计时器。有 3 种基本类型,每种类型都适用于不同的目的。

Use only in a Windows Form application. This timer is processed as part of the message loop, so the the timer can be frozen under high load.

仅在 Windows 窗体应用程序中使用。该计时器作为消息循环的一部分进行处理,因此可以在高负载下冻结计时器。

When you need synchronicity, use this one. This means that the tick event will be run on the thread that started the timer, allowing you to perform GUI operations without much hassle.

当你需要同步时,使用这个。这意味着滴答事件将在启动计时器的线程上运行,使您可以轻松执行 GUI 操作。

This is the most high-powered timer, which fires ticks on a background thread. This lets you perform operations in the background without freezing the GUI or the main thread.

这是最强大的计时器,它在后台线程上触发滴答声。这使您可以在后台执行操作而无需冻结 GUI 或主线程。

For most cases, I recommend System.Timers.Timer.

对于大多数情况,我推荐 System.Timers.Timer。

回答by Brian Rasmussen

Use a timer. Keep in mind that .NET comes with a number of different timers. This articlecovers the differences.

使用计时器。请记住,.NET 带有许多不同的计时器。本文介绍了这些差异。

回答by IvoTops

For this the System.Timers.Timerworks best

为此System.Timers.Timer效果最好

// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it        
myTimer.Enabled = true;

// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }

See Timer Class (.NET 4.6 and 4.5)for details

有关详细信息,请参阅计时器类(.NET 4.6 和 4.5)