Windows.Form.Timer事件滴答调用来自另一个类的问题? [英] Windows.Form.Timer event tick call from another class problem?

查看:91
本文介绍了Windows.Form.Timer事件滴答调用来自另一个类的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.我编写一个winform应用程序.我使用计时器控件.我在班级&中声明了计时器从具有计时器控件的主窗体中,我将调用计时器类.我的代码如下:

-类别:TimerProcess.cs

  class  TimerProcess:计时器
    {
        私有  int  _flag =  0 ;

        公共  int 标志
        {
            获取 {返回 _flag; }
             set  {_flag =  value ; }
        }
        私有  int  _hour =  0 ;

        公共  int 小时
        {
            获取 {返回 _hour; }
             set  {_hour =  value ; }
        } 私有  int  _minute =  0 ;

        公共  int 分钟
        {
            获取 {返回 _minute; }
             set  {_minute =  value ; }
        } 私有  int  _second =  0 ;

        公共  int 第二
        {
            获取 {返回 _second; }
             set  {_second =  value ; }
        } 私有  int  _mode =  0 ;

        公共  int 模式
        {
            获取 {返回 _mode; }
             set  {_mode =  value ; }
        }

        私有  int  _totalTime =  0 ;

        公共  int  TotalTime
        {
            获取 {返回 _totalTime; }
             set  {_totalTime =  value ; }
        }

        私有 字符串 [] run_time = {" "};

        公共 字符串 []运行时间
        {
            获取 {返回运行时间; }
             set  {run_time =  value ; }
        }

        私有  int  increment_num =  0 ;

        公共  int  Increment_num
        {
            获取 {返回 }
             set  {increment_num =  value ; }
        }

        计时器_timer;
        标签_label;

        公共 TimerProcess( int 小时, int 分钟, int 秒, int 模式,标签标签, int 总计,字符串 [] run_time,计时器计时器)
        {
            .小时=小时;
            .Minute=分钟;
            .秒=秒;
            .Mode=模式;
            .TotalTime=总计;
            .Run_time= run_time;
            _label =标签;
            _timer =计时器;
            _timer.Tick + =  EventHandler(timer_Tick);

        }

        公共 静态 字符串 convertSecond2Hour( int 秒)
        {
            TimeSpan t = TimeSpan.FromSeconds(secs);
            字符串小时= 字符串 .Format("  {0:D2}:{1:D2}:{2:D2}",
                                    小时
                                    分钟
                                    t.秒);
            返回小时;
        }

        私有 无效 timer_Tick(对象发​​件人,EventArgs e)
        {
            _timer.Stop(); _timer.Enabled =  true ;
            如果(分钟<   0 )
            {
                分钟=  59 ;
                小时=小时- 1 ;
            }
            如果(第二==  0 )
            {
                Second =  59 ;
                如果(分钟==  0 )
                {
                    分钟=  59 ;
                    小时=小时- 1 ;
                }
                其他
                {
                    分钟=分钟- 1 ;
                }
            }
            _label.Text = "  +小时+ " :" +分钟+  :" +秒;
            Second = Second- 1 ;
            Increment_num + =  1 ;
            如果(标记<  Run_time.Length)
            {
                如果(增量编号== Convert.ToInt32(Run_time [Flag] .ToString()))
                {
                    Increment_num =  0 ;标记+ =  1 ;
                    MessageBox.Show(Run_time [Flag- 1 ].ToString());
                }
            }
            其他 {_timer.Stop(); _label.Text = convertSecond2Hour(TotalTime); }
        }

        公共 无效 timer_start(按钮btnStart)
        {
            btnStart.Enabled =  false ;
            _timer.Start();
        }

        公共 无效 timer_stop(按钮btnStart)
        {
            _timer.Enabled =  false ; _label.Text = convertSecond2Hour(TotalTime);
            btnStart.Enabled =  true ;
        }

        公共 无效 timer_pause(按钮btnPause)
        {
            如果(btnPause.Text == " )
            {
                _timer.Stop();
                btnPause.Text = " ;
            }
            其他 如果(btnPause.Text == " 恢复")
            {
                _timer.Start();
                btnPause.Text = " ;
            }
        }
    } 



-这是我
后面的表单类代码

 公共 部分  class  mainServer:表格
    {
        私有 无效 btnScerioStart_Click(对象发​​件人,EventArgs e)
        {
            initializeTimer() ;
        }

        私有 无效 btnScenarioPause_Click(对象发​​件人,EventArgs e)
        {
            initializeTimer( false  true  false ) ;
        }

        私有 无效 initializeTimer( bool 开始, bool 暂停, bool 停止)
        {
             int  censage_id =  1 ;
             int  hour =  1 ;
             int 分钟=  30 ;
             int  sec =  24 ;
             int  step_number =  5 ;
            字符串 [] run_time =  字符串 [ step_number];
             for ( int  i =  0 ; i <  step_number; i ++)
            {
                run_time [i] =  25 ;
            }
            TimerProcess t =  TimerProcess(小时,分钟,秒, 0 ,lblDuration,Convert.ToInt32(scenarioObject. getTotalDuration(Application.StartupPath + "  /scenarios/scenario [@id ='" + cens_id +  ']/steps/step").ToString()),run_time,timer);
            如果(停止)
            {
                t.timer_stop(btnScenarioStart);
            }
            如果(开始)
            {
                t.timer_start(btnScenarioStart);
            }
            如果(暂停)
            {
                t.timer_pause(btnScenarioPause);
            }

        }

        私有 无效 btnScenarioStop_Click(对象发​​件人,EventArgs e)
        {
            initializeTimer( false  false  true ) ;
        }

    } 



---问题是:如果我单击开始->停止按钮->启动按钮,计时器将创建新的滴答事件,但旧事件仍在运行.如何解决?我只想当我单击停止按钮时,所有事件滴答声都将停止.请帮我.对不起,我的英语:)

解决方案

你好

我不了解您的代码,但:
如果要停止计时器,例如:

 私有 System.Windows.Forms.Timer myTimer; 


使用这个:

 myTimer.Stop(); 


如果要使用许多计时器,则可以创建一个计时器池,如下所示:

 私有字典< string,>  timerPooling = > (); 


例如:

 timerPooling.Add(" ,runningTimer);
timerPooling.Add(" ,jumpingTimer);
timerPooling.Add(" ,restingTimer); 


然后,您可以使用其键来启动或停止任何人:

 timerPooling [" ].Stop();  

我没看到在您的代码中使用Stop()来停止计时器.


您好,

来自MSDN:
计时器用于以用户定义的间隔引发事件,准确度为55毫秒.当Timer.Enabled属性的值为true时,计时器就不会进行垃圾回收.
另外,调用Timer.Start方法与将Enabled设置为true相同.同样,调用Stop方法与将Enabled设置为false相同.

因此,请记住此信息,我会看到您的TimerProcess类存在以下问题:

1.您无处为定时器设置任何间隔.因此您的计时器以默认的100毫秒间隔运行.

2.为什么要从Timer类派生TimerProcess.

3.在timer_tick中,为什么要调用_timer.Stop();? _timer.Enabled = true ??这些是矛盾的. _timer.Stop()将停止计时器,但是将_timer.Enabled设置为true将启动计时器.这似乎是导致问题的原因:
如果我单击开始->停止按钮->开始按钮,计时器将创建新的滴答事件,但旧事件仍在运行."

4.在以下代码中,timer_stop()等效于timer_pause().当您在一个中将Enabled设置为true/false并在另一个中调用Start/Stop时.

  public   void  timer_stop(按钮btnStart)
        {
            _timer.Enabled =  false ; _label.Text = convertSecond2Hour(TotalTime);
            btnStart.Enabled =  true ;
        }

        公共 无效 timer_pause(按钮btnPause)
        {
            如果(btnPause.Text == " )
            {
                _timer.Stop();
                btnPause.Text = " ;
            }
            其他 如果(btnPause.Text == " 恢复")
            {
                _timer.Start();
                btnPause.Text = " ;
            }
        } 



实际上,没有内置的机制可以暂停计时器.您将必须建立自己的.例如,您可以将timer_pause函数编写为:

 TimeSpan _ts;

公共 无效 timer_pause(按钮btnPause)
        {
            如果(btnPause.Text ==& quot; Pause& quot;)
            {
                _ts = DateTime.Now- _lastTimerStartTime;
                _timer.Stop();
                btnPause.Text =&恢复&";
            }
             else   if (btnPause.Text ==& quot; Resume& quot;)
            {
                _timer.Interval = total_interval- _ts.TotalMilliseconds;
                _timer.Start();
                btnPause.Text =&暂停&";
            }
        } 



并相应地在timer_start()和timer_stop()中更新_ts,_timer.Interval和_lastTimerStartTime.

祝您编码愉快!
谢谢


Hi, all. I writing a winform application. I using a Timer control. I declared timer in a class & from main form that have timer control i will call to timer class. My code is below :

- Class: TimerProcess.cs

class TimerProcess : Timer
    {
        private int _flag = 0;

        public int Flag
        {
            get { return _flag; }
            set { _flag = value; }
        }
        private int _hour = 0;

        public int Hour
        {
            get { return _hour; }
            set { _hour = value; }
        } private int _minute = 0;

        public int Minute
        {
            get { return _minute; }
            set { _minute = value; }
        } private int _second = 0;

        public int Second
        {
            get { return _second; }
            set { _second = value; }
        } private int _mode = 0;

        public int Mode
        {
            get { return _mode; }
            set { _mode = value; }
        }

        private int _totalTime = 0;

        public int TotalTime
        {
            get { return _totalTime; }
            set { _totalTime = value; }
        }

        private string[] run_time = { "" };

        public string[] Run_time
        {
            get { return run_time; }
            set { run_time = value; }
        }

        private int increment_num = 0;

        public int Increment_num
        {
            get { return increment_num; }
            set { increment_num = value; }
        }

        Timer _timer;
        Label _label;

        public TimerProcess(int hour, int minute, int second, int mode, Label label, int total, string[] run_time, Timer timer)
        {
            this.Hour = hour;
            this.Minute = minute;
            this.Second = second;
            this.Mode = mode;
            this.TotalTime = total;
            this.Run_time = run_time;
            _label = label;
            _timer = timer;
            _timer.Tick += new EventHandler(timer_Tick);

        }

        public static string convertSecond2Hour(int secs)
        {
            TimeSpan t = TimeSpan.FromSeconds(secs);
            string hour = string.Format("{0:D2}:{1:D2}:{2:D2}",
                                    t.Hours,
                                    t.Minutes,
                                    t.Seconds);
            return hour;
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop(); _timer.Enabled = true;
            if (Minute < 0)
            {
                Minute = 59;
                Hour = Hour - 1;
            }
            if (Second == 0)
            {
                Second = 59;
                if (Minute == 0)
                {
                    Minute = 59;
                    Hour = Hour - 1;
                }
                else
                {
                    Minute = Minute - 1;
                }
            }
            _label.Text = "0" + Hour + ":" + Minute + ":" + Second;
            Second = Second - 1;
            Increment_num += 1;
            if (Flag < Run_time.Length)
            {
                if (Increment_num == Convert.ToInt32(Run_time[Flag].ToString()))
                {
                    Increment_num = 0; Flag += 1;
                    MessageBox.Show(Run_time[Flag - 1].ToString());
                }
            }
            else { _timer.Stop(); _label.Text = convertSecond2Hour(TotalTime); }
        }

        public void timer_start(Button btnStart)
        {
            btnStart.Enabled = false;
            _timer.Start();
        }

        public void timer_stop(Button btnStart)
        {
            _timer.Enabled = false; _label.Text = convertSecond2Hour(TotalTime);
            btnStart.Enabled = true;
        }

        public void timer_pause(Button btnPause)
        {
            if (btnPause.Text == "Pause")
            {
                _timer.Stop();
                btnPause.Text = "Resume";
            }
            else if (btnPause.Text == "Resume")
            {
                _timer.Start();
                btnPause.Text = "Pause";
            }
        }
    }



-- This is my form class code behind

public partial class mainServer : Form
    {
        private void btnScerioStart_Click(object sender, EventArgs e)
        {
            initializeTimer(true, false, false);
        }

        private void btnScenarioPause_Click(object sender, EventArgs e)
        {
            initializeTimer(false, true, false);
        }

        private void initializeTimer(bool start, bool pause, bool stop)
        {
            int scenario_id = 1;
            int hour = 1;
            int minute = 30;
            int sec = 24;
            int step_number = 5;
            string[] run_time = new string[step_number];
            for (int i = 0; i < step_number; i++)
            {
                run_time[i] = 25;
            }
            TimerProcess t = new TimerProcess(hour, minute, sec, 0, lblDuration, Convert.ToInt32(scenarioObject.getTotalDuration(Application.StartupPath + "\\Xml\\Scenario.xml", "/scenarios/scenario[@id='" + scenario_id + "']/steps/step").ToString()), run_time, timer);
            if (stop)
            {
                t.timer_stop(btnScenarioStart);
            }
            if (start)
            {
                t.timer_start(btnScenarioStart);
            }
            if (pause)
            {
                t.timer_pause(btnScenarioPause);
            }

        }

        private void btnScenarioStop_Click(object sender, EventArgs e)
        {
            initializeTimer(false, false, true);
        }

    }



--- Issue is: if i click start -> stop button -> start buton , timer will creat new tick event but old event still run. How to fix it? I only want when i click stop button then all event tick will stop. Please help me. Sorry for my english :)

解决方案

Hello

I don''t understand your code but:
If you want to stop a timer, for example:

private System.Windows.Forms.Timer myTimer;


Use this:

myTimer.Stop();


If you want to use many timers, you can create a Timer pooling like this:

private Dictionary<string,> timerPooling = new Dictionary<string,>();


For example:

timerPooling.Add("runningTimer", runningTimer);
timerPooling.Add("jumpingTimer", jumpingTimer);
timerPooling.Add("restingTimer", restingTimer);


Then you can start or stop anyone with using its key:

timerPooling["jumpingTimer"].Stop();



I didn''t see using Stop() in your code for stoping the timer.


Hi,

From MSDN:
A Timer is used to raise an event at user-defined interval with an accuracy of 55msec. And the timer is not subject to garbage collection when the value of Timer.Enabled property is true.
Also calling the Timer.Start method is the same as setting Enabled to true. Likewise, calling the Stop method is the same as setting Enabled to false.

So keeping this info in mind I see following issues with your TimerProcess class:

1. You have nowhere set any interval for your timer. So your timer is running with default interval of 100msec.

2. Why are you deriving your TimerProcess from Timer class.

3. In timer_tick why are you calling _timer.Stop(); _timer.Enabled = true ?? These are contradictory. _timer.Stop() will stop the timer, but setting _timer.Enabled to true will start the timer. This looks like the cause for your issue:
"if i click start -> stop button -> start buton , timer will creat new tick event but old event still run. "

4. In the following code, timer_stop() is equivalent to timer_pause(). As you are setting Enabled to true/false in one and calling Start/Stop in other.

public void timer_stop(Button btnStart)
        {
            _timer.Enabled = false; _label.Text = convertSecond2Hour(TotalTime);
            btnStart.Enabled = true;
        }

        public void timer_pause(Button btnPause)
        {
            if (btnPause.Text == "Pause")
            {
                _timer.Stop();
                btnPause.Text = "Resume";
            }
            else if (btnPause.Text == "Resume")
            {
                _timer.Start();
                btnPause.Text = "Pause";
            }
        }



Actually there is no inbuilt mechanism to pause a timer. You would have to build your own. For ex, you can write your timer_pause function as:

TimeSpan _ts;

public void timer_pause(Button btnPause)
        {
            if (btnPause.Text == &quot;Pause&quot;)
            {
                _ts= DateTime.Now- _lastTimerStartTime;
                _timer.Stop();
                btnPause.Text = &quot;Resume&quot;;
            }
            else if (btnPause.Text == &quot;Resume&quot;)
            {
                _timer.Interval=total_Interval- _ts.TotalMilliseconds;
                _timer.Start();
                btnPause.Text = &quot;Pause&quot;;
            }
        }



And update the _ts, _timer.Interval and _lastTimerStartTime accordingly in timer_start()and timer_stop().

Happy Coding!!
Thanks


这篇关于Windows.Form.Timer事件滴答调用来自另一个类的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆