C# 如何定期执行函数

C# 如何定期执行函数,c#,timer,C#,Timer,如何连续每40秒执行一次C#方法?您应该使用.net中提供的计时器功能 这是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

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

您应该使用.net中提供的计时器功能

这是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
    }
}

查看System.Threading.Timer

var timer = new System.Threading.Timer(new TimerCallback(YourMethod), null, 40000, Timeout.Infinite);
private void YourMethod(object state)
{
    //Magic
    timer.Change(40000, Timeout.Infinite);
}
试试这个

<asp:UpdatePanel runat="server" UpdateMode="Always">
    <ContentTemplate>
    <asp:Timer  ID="timer" runat="server" Interval="40000"></asp:Timer>
    </ContentTemplate>
</asp:UpdatePanel>

我可以建议使用Quartz.Net。您可以实施Quartz.Net计划的服务。您只需要按照您想要的方式配置触发器。

到目前为止,您得到了什么?它在哪里运行?在服务器上?看起来像是:我被告知不要用链接回答;)最好使用
System.Threading.Timer
,因为你链接的那个也可以吞下异常。我的答案基于他可能理解的内容,因为他不能谷歌“每40秒运行一次函数c#”(这是每2秒一次,但已经足够接近了),然后点击第一个链接——我假设线程可能是一个触手可及的功能。但是@Moo Juice你是对的,它是一个更好的实现。应该是40000而不是40000是的,计时器在40秒后启动,但没有被要求立即启动,计时器在每40秒后运行一次。请尝试使用计时器。更改(40000,Timeout.Infinite)重置计时器,它将再次运行;)啊,我不知道。改变了投票:)这个答案更可取,因为它使用了
System.Threading.Timer
    protected void Page_Load(object sender, EventArgs e)
    {
       callyourfunction();
     }