Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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
C#
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
C#
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 :)
Posted
Updated 29-Apr-12 19:20pm
v3
Comments
Sergey Alexandrovich Kryukov 30-Apr-12 12:34pm    
Why do you need all that? What are your trying to achieve?
--SA
Silent Guardian 30-Apr-12 17:09pm    
what do you wanna achieve?
most of TimerProcess class properties can be implemented directly.

Hello

I don't understand your code but:
If you want to stop a timer, for example:
C#
private System.Windows.Forms.Timer myTimer;

Use this:
C#
myTimer.Stop();

If you want to use many timers, you can create a Timer pooling like this:
C#
private Dictionary<string,> timerPooling = new Dictionary<string,>();

For example:
C#
timerPooling.Add("runningTimer", runningTimer);
timerPooling.Add("jumpingTimer", jumpingTimer);
timerPooling.Add("restingTimer", restingTimer);

Then you can start or stop anyone with using its key:
C#
timerPooling["jumpingTimer"].Stop();


I didn't see using Stop() in your code for stoping the timer.
 
Share this answer
 
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.

C#
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:

C#
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
 
Share this answer
 
Comments
Ankush Bansal 3-May-12 5:32am    
Thanks for vote of 5!! appreciate that

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900