c# - In what time interval is the conditions in a while clause checked? -


how wait specified time while showing remaining time wait?

i solved feel bad way it:

//this running in backgroundworker:  stopwatch watch = new stopwatch(); watch.start(); while(watch.elapsedmilliseconds != secondstowait * 1000) {     timetonextrefresh = ((secondstowait * 1000) - watch.elapsedmilliseconds) / 1000;     thread.sleep(1); }                    watch.stop();   

so here guessing condition (watch.elapsedmilliseconds != secondstowait * 1000) checked every millisecond.

so main question is; in period condition of while checked and/or how improve code i've written?

it depends on what's code inside while loop!

for example, if write long/time-consuming code in while loop, each iteration of while loop, or course, longer while loop has short/fast code.

compare these 2 while loops:

while (true) {     console.writeline("hello"); } 

and

while (true) {     console.beep(5000); } 

each iteration of first while loop faster of second 1 because console.beep(5000) takes 5 seconds , console.writeline takes fraction of second.

so can't rely on while loops count time.

this should do:

create instance of system.windows.forms.timer, not system.timers.timer nor system.threading.timer. find first 1 useful (others more advanced).

timer timer = new timer(); timer.interval = 1000; // 1000 means 1000ms aka 1 second timer.tick += timerticked; timer.start(); 

now compiler tell timerticked not defined, let's go define that:

private void timerticked(object sender, eventargs e) {  } 

now you're set. code in timerticked called every 1 second.

let's want measure time of 10 seconds. after 10 seconds, want something. first create variable called secondsleft in class level:

int secondsleft = 10; 

now in timerticked, want check whether secondsleft 0. if is, something, else, minus one:

if (secondsleft == 0) {     dosomething(); } else {     secondsleft--; } 

and secondsleft is time remaining! can display on label or something.

to pause timer, simply

timer.stop(); 

Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -