C#Timer没有触发信息

时间:2016-02-09 10:33:57

标签: c# timer

我的c#应用程序中有两个计时器。但是其中一个计时器不起作用。 这是我用于我的计时器的代码:

System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 600000;
timer.Elapsed += new ElapsedEventHandler(call1);
timer.Start();

System.Timers.Timer alerttimer= new System.Timers.Timer();
alerttimer.Interval = 600000; 
alerttimer.Elapsed += new ElapsedEventHandler(call2);
alerttimer.Start();

这正是我在项目中拥有它的方式,一个接一个的计时器。第一个计时器执行事件,但另一个计时器不执行。 我错过了一些不允许两个计时器都工作的东西吗? 谢谢。

编辑:这是我的方法的摘录,还有更多,但他们所做的只是获取ram,cpu,驱动器和服务信息。

 public static void call1(object sender, ElapsedEventArgs args)
    {

        PerformanceCounter ramCount = new PerformanceCounter("Memory", "Available MBytes");
        PerformanceCounter cpuCount = new PerformanceCounter("Processor", "% Processor Time", "_Total");
        Console.WriteLine("Press any key to view other information...\n");
        Console.WriteLine("CPU and RAM information");

        double perf = cpuCount.NextValue();
        Thread.Sleep(1000);
        perf = cpuCount.NextValue();
        Console.WriteLine("CPU Performance: " + perf + " %");
        ServerStats.cpuLoad = perf;
    }

   public static void call2(object sender, System.Timers.ElapsedEventArgs args)
        {
            PerformanceCounter ramAlert = new PerformanceCounter("Memory", "Available MBytes");

            double ram1, ram2, ram3, ram4, ram5, ram6, ram7, ram8, ram9, ram0;
            ram0 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram1 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram2 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram3 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram4 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram5 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram6 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram7 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram8 = ramAlert.NextValue();
            Thread.Sleep(50000);
            ram9 = ramAlert.NextValue();
            Thread.Sleep(50000);

            double total = ram0 + ram1 + ram2 + ram3 + ram4 + ram5 + ram6 + ram7 + ram8 + ram9;
            double average = total / 10;

            if (average >= 90)
            {
                string hostName = System.Net.Dns.GetHostName();

                Alert.serverName = hostName;
                Alert.alertType = "RAM alert: " + average;
            }

1 个答案:

答案 0 :(得分:0)

所以我发现了问题所在。首先发布call2有一个延迟,因为Thread.Sleep(50000)用于计算ram的平均值。所以基本上,计时器正在开火,但经过一段时间的延迟。

其次,此程序是一项服务,因此我必须在服务属性中更改我的版本和产品代码,以防止Visual Studio运行旧版本。

感谢大家的帮助。