简体   繁体   中英

Why System.Timer doesn't change class member variable?

I have a while loop and in this loop, there is a if condition. But condition will be changed by a timer. But timer never change global variable. I cant understand. Where is the problem?

Example:

bool enterHere = false;
Timer timer = new Timer(); //Timer Started

private void timer_Tick(object Sender, ...)
{
    enterHere = true;
}

private void function()
{
   while(...)
   {
       if(enterHere)
       {
           //Never enter here
       }
   }
}

As another lesson in why you should always post your real code when asking questions on SO...

It appears the solution to your problem is quite a bit simpler than the other answers suggest. The timer's Tick event is never going to be raised, thus the value of the enterHere variable is never going to be changed, because you never actually start the timer. More specifically, this line is incorrect:

Timer timer = new Timer(); //Timer Started

The constructor does not start the timer; you need to call its Start method . This is confirmed by the documentation , which says:

When a new timer is created, it is disabled; that is, Enabled is set to false. To enable the timer, call the Start method or set Enabled to true.

Absolutely no reason to muck about with things like Application.DoEvents if you don't have to.

I assume you're using a System.Windows.Forms.Timer in which case the Tick event will run on the same thread as your function() . You can put

Application.DoEvents();

Inside your loop to get the timer to tick. Alternatively you could use an other timer (such as the System.Threading one), which executes on a different thread.

What else are you doing in the WHILE(...) loop and have you checked the processor usage when your code is running? If the loop is running very quickly there is no time for your app to process it's messages and react to the timer message.

As deltreme says, inserting Application.DoEvents(); in the loop should give it a chance to process the message.

Ideally the timer should be running in a different thread if you have a loop like that. The timer will never be able to raise the event.

Alteratively you could call DoEvents() to allow the timer to do it's work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM