Share via

timer elspsed even after timing stop

Vivek Kumar 21 Reputation points
2022-02-17T13:36:20.163+00:00

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;

using System.Text;
using System.Threading.Tasks;
using System.Timers;

using System.Collections;
using System.Configuration;
using System.Xml;

namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
System.Timers.Timer RefObject;
public Form1()
{
InitializeComponent();
}

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        CreateTimer();
    }

    private void CreateTimer()
    {
        System.Timers.Timer tmrSync = new System.Timers.Timer();
        RefObject = tmrSync;
        tmrSync.Interval = 3000;
        tmrSync.Elapsed += new ElapsedEventHandler(timerSync_Tick);
        tmrSync.Enabled = true;
        tmrSync.Start();
    }



    private void DisposeTimer()
    {

        RefObject.Enabled = false;
        RefObject.Stop();
    }

    private void timerSync_Tick(object sender, EventArgs e)
    {
        try
        {


            RefObject.Elapsed -= new ElapsedEventHandler(timerSync_Tick);
            textBox1.Text += "Secondhit " + Environment.NewLine;

            DisposeTimer();

            //Perform Operation
            textBox1.Text += "Hit " + Environment.NewLine;
            Application.DoEvents();
            CreateTimer();
        }
        catch (Exception)
        {
            DisposeTimer();
        }
    }
}

}

Developer technologies | Windows Forms
0 comments No comments

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,606 Reputation points Volunteer Moderator
    2022-02-17T15:23:31.95+00:00

    Here is an alternate approach.

    Timer code is outside of a form, an event in this case pushes simple text to a caller of this class.

    Start and Stop methods do just that, start and stop the Timer.

    using System.Threading;
    using Timer = System.Threading.Timer;
    
    namespace WorkingWithTimer.Classes
    {
        public class Utilities
        {
            /// <summary>
            /// How long between intervals, adjust as needed or use Initialize overload
            /// </summary>
            private static int _dueTime = 6000 * 10;
            private static Timer _workTimer;
    
            public delegate void MessageHandler(string message);
            /// <summary>
            /// Optional event
            /// </summary>
            public static event MessageHandler Message;
            /// <summary>
            /// Flag to determine if timer should initialize 
            /// </summary>
            public static bool ShouldRun { get; set; } = true;
    
            private static void Initialize()
            {
                if (!ShouldRun) return;
    
                _workTimer = new Timer(Dispatcher);
                _workTimer.Change(_dueTime, Timeout.Infinite);
            }
    
            private static void Initialize(int dueTime)
            {
                if (!ShouldRun) return;
                _dueTime = dueTime;
                _workTimer = new Timer(Dispatcher);
                _workTimer.Change(_dueTime, Timeout.Infinite);
            }
            private static void Dispatcher(object e)
            {
                Worker();
                _workTimer.Dispose();
                Initialize();
            }
    
            public static void Start()
            {
                Initialize();
                Message?.Invoke("Started");
            }
            public static void Stop()
            {
                _workTimer.Dispose();
                Message?.Invoke("Stopped");
            }
    
            /// <summary>
            /// Where work is done
            /// </summary>
            private static void Worker()
            {
                Message?.Invoke("Performing work");
            }
    
        }
    }
    

    In form load

    Utilities.Message += OnMessageReceived;
    

    Event for above

    private void OnMessageReceived(string message) 
        => listBox1.InvokeIfRequired(lb => lb.Items.Add(message));
    

    Extension method for above

    public static class Extensions
    {
        public static void InvokeIfRequired<T>(this T control, Action<T> action) where T : ISynchronizeInvoke
        {
            if (control.InvokeRequired)
            {
                control.Invoke(new Action(() => action(control)), null);
            }
            else
            {
                action(control);
            }
        }
    }
    

    Full code
    https://github.com/karenpayneoregon/windows-forms-csharp/tree/Version3/WorkingWithTimer

    Was this answer helpful?

    0 comments No comments

  2. Viorel 127K Reputation points
    2022-02-17T14:37:52.427+00:00

    Try using the System.Windows.Forms.Timer and remove the DoEvents line.

    Since you call CreateTimer, a new timer is recreated. (Maybe you should use a single timer).

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.