这样的Timer怎么使?用一个Timer控件去控制方法“GetPic()”的执行,执行的过程是这样的,每五分钟执行一次,但一共只执行两次,不能一直执行下去这样的方法应该怎么写呢???

解决方案 »

  1.   

    定义全局变量 int i=0;定时器函数里  
    if(i==2)
    {
    timer.stop();
    }
    else
    {
    i++;
    }
      

  2.   

    也可以使用局部静态变量static int i
      

  3.   


    using System;  
    using System.Timers;namespace Select
    {
        public class RunTime
        {
            private Timer _timer = new Timer();
            private int i = 0;        public void GetPic(object sender, ElapsedEventArgs e)
            {
                if (i != 2)
                {
                    Console.WriteLine("第" + i.ToString() + "次调用");
                    i++;
                }
                else
                {
                    _timer.Stop();   
                    Console.WriteLine("停止调用了"); 
                }
            }        public void Run()
            {
                _timer.Interval = 5*60*1000;
                _timer.Elapsed += new ElapsedEventHandler(GetPic);
                _timer.Start();
            }
        }    public class MainClass
        {
            static void Main(string[] args)
            {
                RunTime runTime = new RunTime();
                runTime.Run();
                Console.Read();
            }
        }
    }