multithreading - Why the threading.timer doesn't execute every 1ms in my code? -
i set threading.timer interval time 100ms. console output, time interval 1.6s. why doesn't write line in console output every 100ms? want 1ms accurate timer, can use in code simulate plc real time system.
module module1 class stateobjclass ' used hold parameters calls timertask public somevalue integer public timerreference system.threading.timer public timercanceled boolean public glo_tick long end class public stateobj new stateobjclass public long_temp1 long public int16_temp1 int16 sub runtimer() stateobj.timercanceled = false stateobj.somevalue = 1 dim timerdelegate new threading.timercallback(addressof timertask) ' create timer calls procedure every 2 seconds. ' note: there no start method; timer starts running ' instance created. dim timeritem new system.threading.timer(timerdelegate, stateobj, _ 0, 1) stateobj.timerreference = timeritem ' save reference dispose. dim boolean = false dim state int16 while true ' run ten loops. 'system.threading.thread.sleep(1000) ' wait 1 second. select case state case 0 if long_temp1 = stateobj.glo_tick else = true long_temp1 = stateobj.glo_tick console.writeline("a=" & & now) end if state = 1 exit select case 1 calculate_interval(long_temp1, int16_temp1) if int16_temp1 > 100 = false long_temp1 = stateobj.glo_tick console.writeline("a=" & & now) state = 2 end if exit select case 2 calculate_interval(long_temp1, int16_temp1) if int16_temp1 > 100 = true long_temp1 = stateobj.glo_tick console.writeline("a=" & & now) state = 1 end if exit select end select end while stateobj.timercanceled = true ' request dispose of timer object. end sub sub timertask(byval stateobj object) dim state stateobjclass = ctype(stateobj, stateobjclass) if state.timercanceled ' dispose requested. system.diagnostics.debug.writeline("done " & now) state.timerreference.dispose() end if system.threading.interlocked.increment(state.glo_tick) end sub sub main() runtimer() console.read() end sub function calculate_interval(byval intervalstart long, byref interval_ms int16) int16 interval_ms = convert.toint16(stateobj.glo_tick - intervalstart) return interval_ms end function
end module
Comments
Post a Comment