繁体   English   中英

C#暂停程序执行

[英]C# Pause Program Execution

我正在编写一个程序,每10或15分钟执行一次操作。 我希望它一直在运行,所以我需要一些处理能力便宜的东西。 到目前为止我所看到的似乎表明我想使用Timer。 这是我到目前为止的代码片段。

class Program {
    private static Timer timer = new Timer();

    static void Main(string[] args) {
        timer.Elapsed += new ElapsedEventHandler(DoSomething);
        while(true) {
            timer.Interval = TimerMilliseconds(); // The duration of the wait will differ each time
            timer.Enabled=true;
        }
    }
}

这里的问题是while循环只是保持快速执行。 如何停止执行直到计时器结束。 我的程序真的不需要多线程。 Timer是否适合这项工作?

预先感谢您的任何帮助!

更新:对不起混淆。 我已经实现了DoSomething方法。 我只是没有包括它,因为我不相信它是我的问题的一部分。

一旦指定的间隔过去, Timer将触发Elapsed事件。

我会做这样的事情:

private static Timer timer = new Timer();

static void Main(string[] args) 
{
    timer.Elapsed += new ElapsedEventHandler(DoSomething);
    timer.Interval = TimerMilliseconds(); // The duration of the wait will differ each time
    timer.Enabled=true;

    Console.ReadKey(); //Wait for keypress to terminate
}

您也可以将其实现为服务,这样您就不必像Console.ReadKey那样使用阻塞调用来阻止程序终止。

最后,您可以只更改事件处理程序中的间隔:

static void DoSomething(...)
{
   timer.Stop();
   timer.Interval = TimerMilliseconds();

   ...
   timer.Start();
}

这段代码的问题在于你正在使用一个循环来设置TimerIntervalEnabled属性,它会反复执行所述赋值 - 它不会等待定时器以某种方式执行。

如果你的应用程序不需要多线程,那么你最好简单地在执行之间调用Thread.Sleep

class Program {    
    static void Main(string[] args) {
        while(true) {
            Thread.sleep(TimerMilliseconds()); // The duration of the wait will differ each time
            DoSomething();
        }
    }
}

完全删除while循环。

DoSomething()函数内部(一旦实现)在启动时停止计时器,并在重新启动计时器之前重置间隔。

从你的逻辑中取出计时器和循环。 只需使用Windows调度程序在15分钟后执行您的程序。 或者您可以使用Windows服务。 请阅读Best Timer以在Windows服务中使用

我想评论和答案已经提供了你需要的提示,但定时器MSDN文档实际上提供了一个很好的例子。 在我看来,Timer方法有点整洁,更容易阅读您的意图并抽象出调用您的预定代码的细节。

这是使用ManualResetEvent和WaitOne()的另一种替代方法。 这将允许您暂停主线程,而不必担心它会被错误的按键意外杀死。 您还可以在满足特定条件时设置()MRE以允许应用程序正常退出:

class Program
{

    private static Timer timer;
    private static ManualResetEvent mre = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        timer = new Timer(TimerCallback, null, 0, (int)TimeSpan.FromMinutes(15).TotalMilliseconds);
        mre.WaitOne();
    }

    private static void TimerCallback(object state)
    {
        // ... do something in here ...
        Console.WriteLine("Something done at " + DateTime.Now.ToString());
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM