如何定期执行一个函数

Gaj*_*esh -1 c# timer

如何连续每40秒执行一次C#方法?

Rya*_*ugh 5

您应该使用.net中提供的Timer功能

文档

这是来自MSDN的代码,略有变化.

public class Timer1
{
    private static System.Timers.Timer aTimer;

    public static void Main()
    {

        // Create a timer with a fourty second interval.
        aTimer = new System.Timers.Timer(40000);

        // Hook up the Elapsed event for the timer.
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);    


        // If the timer is declared in a long-running method, use 
        // KeepAlive to prevent garbage collection from occurring 
        // before the method ends. 
        //GC.KeepAlive(aTimer);
    }

    // Specify what you want to happen when the Elapsed event is  
    // raised. 
    private static void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        //Code that needs repeating every fourty seconds
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`System.Threading.Timer`要好得多,因为你链接的那个也可以吞下异常. (6认同)