C# Timer, or better use a thread?

Markus Freitag 3,786 Reputation points
2022-10-27T18:37:14.443+00:00

Hello,

I am looking for a good simple way to start and stop timers.
In C++ there are SetTimer, KillTimer.
For different requests. (Currently up to 10 different, so 10 different timers).

Picture:
254749-requestresponsetimeout.png

1 --> Start Request --> Start Timer
2 --> Response received --> Stop Timer
Or Timeout

I can set a timer with ID
ID=101
Timeout=1000
SetTimer(101, 1000)
KillTimer(101);

Then there is the function OnTimer

Is there anything similar in C#?

void CustomGroup::OnTimer(unsigned int iTimerId)  
{  
	CString sHelp;  
	switch (iTimerId - 1)  
	{  
	default:  
		sHelp.Format("Unknown Timer id= '%d' TimeOut= '%d'", iTimerId, m_lTimeout);  
		break;  
	case STD_REQUEST_ORDER_NO:  
    	// Show error  
		OrderNoRes(STD_REQUEST_ORDER_NO, "No answer");  
		break;  
  
//////////////////////////  
  
My attempts, approaches are listed here below.  
  
public System.Threading.Timer AsyncProgramChangeTimer = null;  
public System.Threading.Timer AsyncProgramChangeTimer2 = null;  
  
AsyncProgramChangeTimer = new System.Threading.Timer((o) =>  
{  
	if (chkDone.Checked)  
	{  
		AsyncProgramChangeTimer.Change(Timeout.Infinite, Timeout.Infinite);  
		AsyncProgramChangeTimer = null;  
	}  
	else  
	{  
		AsyncProgramChangeTimer.Change(1000, Timeout.Infinite);  
		Log.Info($"##Repeat Timer### {DateTime.Now.ToLocalTime()}");  
	}  
}, null, 4000, Timeout.Infinite);  
  
  
AsyncProgramChangeTimer2 = new System.Threading.Timer(CallBackTimer2, null, 8000, Timeout.Infinite);  
private void CallBackTimer2(Object state)  
{  
	if (chkDone.Checked)  
	{  
		AsyncProgramChangeTimer2.Change(Timeout.Infinite, Timeout.Infinite);  
		AsyncProgramChangeTimer2 = null;  
	}  
	else  
	{  
		AsyncProgramChangeTimer2.Change(1000, Timeout.Infinite);  
	}  
}  
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,386 Reputation points
    2022-10-27T23:39:38.617+00:00

    Checkout the following,

    Base code

    using Timer = System.Threading.Timer;  
      
    namespace ThreadingTimerApp.Classes;  
      
    public class TimerHelper  
    {  
        /// <summary>  
        /// How long between intervals, currently 30 minutes  
        /// </summary>  
        public static int Interval = 1000 * 60 * 30;  
        private static Timer _workTimer;  
        public static ActionContainer ActionContainer;  
      
        /// <summary>  
        /// Text to display to listener   
        /// </summary>  
        /// <param name="message">text</param>  
        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;  
      
        /// <summary>  
        /// Default initializer  
        /// </summary>  
        private static void Initialize()  
        {  
            if (!ShouldRun) return;  
            _workTimer = new Timer(Dispatcher);  
            _workTimer.Change(Interval, Timeout.Infinite);  
        }  
      
        /// <summary>  
        /// Initialize with time to delay before triggering <see cref="Worker"/>  
        /// </summary>  
        /// <param name="dueTime"></param>  
        private static void Initialize(int dueTime)  
        {  
            if (!ShouldRun) return;  
            Interval = dueTime;  
            _workTimer = new Timer(Dispatcher);  
            _workTimer.Change(Interval, Timeout.Infinite);  
        }  
        /// <summary>  
        /// Trigger work, restart timer  
        /// </summary>  
        /// <param name="e"></param>  
        private static void Dispatcher(object e)  
        {  
            Worker();  
            _workTimer.Dispose();  
            Initialize();  
        }  
      
        /// <summary>  
        /// Start timer without an <see cref="Action"/>  
        /// </summary>  
        public static void Start()  
        {  
            Initialize();  
            Message?.Invoke("Started");  
        }  
        /// <summary>  
        /// Start timer with an <see cref="Action"/>  
        /// </summary>  
        public static void Start(Action action)  
        {  
            ActionContainer = new ActionContainer();  
            ActionContainer.Action += action;  
      
            Initialize();  
      
            Message?.Invoke("Started");  
      
        }  
        /// <summary>  
        /// Stop timer  
        /// </summary>  
        public static void Stop()  
        {  
            _workTimer.Dispose();  
            Message?.Invoke("Stopped");  
        }  
      
        /// <summary>  
        /// If <see cref="ActionContainer"/> is not null trigger action  
        /// else alter listeners it's time to perform work in caller  
        /// </summary>  
        private static void Worker()  
        {  
            Message?.Invoke("Performing work");  
            ActionContainer?.Action();  
        }  
    }  
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Castorix31 83,206 Reputation points
    2022-10-27T19:15:08.983+00:00

    There are several timers in .NET: Timers

    1 person found this answer helpful.
    0 comments No comments