Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9210401
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T01:04:08+00:00 2026-06-18T01:04:08+00:00

I have an Elapsed method in which I have a while loop. If the

  • 0

I have an Elapsed method in which I have a while loop. If the timer is disabled/stopped from another thread, I would like this loop to stop. Can I rely on the timer’s Enabled property in the Elapsed method for this or should I create a “volatile bool timerEnabled” variable just to be sure. My testings show that it’s OK, but I’d like to be sure of this before putting it in production.

This is what I’m trying to achieve (not actual code but close)

private volatile bool isElapsedAlreadyRunning

void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    if (!isElapsedAlreadyRunning)   // to prevent reentrance
    {
        isElapsedAlreadyRunning = true;
        try 
        {
            while (myTimer.Enabled && some other condition)
            {
                do stuff
            }
        }
        finally
        {
            isElapsedAlreadyRunning = false;
        }
    }
}

myTimer.Start() and myTimer.Stop() are in other methods that can be called frrom other threads

I’m using the System.Timers.Timer class

If you have any other comment or see any pitfall in this design feel free to comment 🙂

Thanks


Edit :

Man, threading is hard. Based on the answers and other stackoverflow questions (this answer particularly) this would be the way to do it (I hope this time it’s OK)

public class NoLockTimer : IDisposable
{
    private readonly System.Timers.Timer _timer;

    private bool _isTimerStopped = false;
    private readonly object _isTimerStoppedLock = new object();

    public NoLockTimer()
    {
        _timer = new System.Timers.Timer { AutoReset = false, Interval = 1000 };

        _timer.Elapsed += delegate
        {
            try
            {
                while (!IsTimerStopped && some other condition) 
                {
                    // do stuff
                }
            }
            catch (Exception e)
            {
                // Do some logging
            }
            finally
            {
                if (!IsTimerStopped) 
                {
                    _timer.Start(); // <- Manual restart.
                }
            }
        };

        _timer.Start();
    }

    public void Stop()
    {
        IsTimerStopped = true;
        if (_timer != null)
        {
            _timer.Stop();
        }
    }

    private bool IsTimerStopped
    {
        get 
        {
            lock (_isTimerStoppedLock)
            {
                return _isTimerStopped;
            }
        }
        set 
        {
            lock (_isTimerStoppedLock)
            {
                _isTimerStopped = value;
            }
        }
    }

    public void Dispose()
    {
        Stop();
        if (_timer != null)
        {
            _timer.Dispose();
        }
    }
} 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T01:04:09+00:00Added an answer on June 18, 2026 at 1:04 am

    No, this is not safe. The Elapsed event handler is called on a threadpool thread. You cannot predict when that thread actually calls your method, it depends on what other TP threads are running in the process. Having two calls in flight at the same time is technically possible. Which makes the volatile keyword on the isElapsedAlreadyRunning variable not nearly good enough to ensure that the method is thread-safe, you must use the lock keyword or Monitor.TryEnter() instead.

    This problem disappears when you set the Timer’s AutoReset property to false. Be sure to restart the timer in a finally block, another nasty problem with the Timer.Elapsed event is that exceptions get swallowed without diagnostic. System.Threading.Timer is an all-around better timer with fewer surprises like this.

    The Timer.Enabled property has a similar problem, you’ll always see it late.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Lets say I have a Timer which has the Elapsed event handled. What thread
I have two times in PHP and I would like to determine the elapsed
I would like (in an ELEGANT way) to use some custom method attribute which
I have this extension method to disable a timer after a given interval. Is
I have a timer that needs to not process its elapsed event handler at
have written this little class, which generates a UUID every time an object of
Have a procedure which looks like Procedure TestProc(TVar1, TVar2 : variant); Begin TVar1 :=
I have my application in which in three datagridview independently in three thread load
I would have expected delegates generated from expression trees to achieve roughly the same
I have the following code which uses the System.Timers.Timer: // an instance variable Timer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.