Reputation: 803
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
}
}
}
Upvotes: 2
Views: 856
Reputation: 244782
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 theStart
method or setEnabled
to true.
Absolutely no reason to muck about with things like Application.DoEvents
if you don't have to.
Upvotes: 3
Reputation: 27367
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
Upvotes: 0
Reputation: 10327
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.
Upvotes: 1
Reputation: 26446
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.
Upvotes: 2