c# - Update UI element from thread -
i try create in windows phone timer update every 10-15 ms (for ui element). , want have opportunity append time. create timespan , dispatchertimer interval = 15 ms. every 15 ms call event subtract 15 ms timespan , when timespan <= 0 call method. when set timespan 4 seconds (for example) in life passed more 4 sec 4,6 sec. tryed use async/await did't work. tryed use system.threading don't know how update element create in other thread.
so every 15 ms call event subtract 15 ms timespan , when timespan <= 0 call method.
your logic flawed. can't possibly update timespan way because:
- as stephen cleary mentioned in answer, have no guarantee timer fire @ 15 ms
- even if did, doesn't take account time needed update timespan (say takes 1ms compute new timespan, timer drift of 1ms every 15ms)
to have accurate time, need store timestamp @ started (retrieve using datetime.utcnow
. every time timer tick, take new timestamp , substract 1 saved. way, know how time has passed , timer never drift.
private datetime start; // set datetime.utcnow when starting timer void timer_tick(object sender, eventargs e) { // compute new timespan var timespan = datetime.utcnow - start; // whatever (check if it's greater 4 seconds, display it, ...) }
Comments
Post a Comment