multithreading - Marshalling call to main thread from System.Timers.Timer -


i have tough question (for me @ least). i'm working on windows service written in vb.net. i'm using system.timers.timer class periodically call delegate method see if there work do. timing of processing not critical , have attempted prevent re-entry worker method disabling timer method invoked , starting again @ end.

however, timer class elapsed events occur on different thread. searching online, people using windows forms implement isynchronize interface marshal call originating thread. ideally don't want use windows forms achieve this. there easy way re-direct call original thread?

alternatively there framework class can inherit this? or @ worst simple implementation of isynchronize?

imports system.timers imports system.io imports system.data   public class application     implements idisposable   private withevents _timer timer    private sub sleeptimercallback(sender object, e elapsedeventargs) handles _timer.elapsed      ' todo need find way bring method on main thread.      ' temporarily disable timer elapsed event don't have event re-entrance.     if me._timer.enabled = true me._timer.enabled = false      ' work.      ' re-enable timer elapsed event.     _timer.enabled = true  end sub  end class 

your timer enabling / disabling code has subtle bug. have:

if me._timer.enabled = true me._timer.enabled = false  ' work  ' re-enable timer _timer.enabled = true 

so if timer disabled on entry, code still executes. granted, shouldn't multiple calls, conditional check there useless.

a better way initialize timer autoreset set false. makes timer tick once. then, @ end of event handler, call start again restart timer. way can't possibly multiple concurrent calls handler.

system.timers.timer has unfortunate property of squashing exceptions, pointed out in documentation:

the timer component catches , suppresses exceptions thrown event handlers elapsed event.

so if event handler throws exception never know it. except timer won't re-enabled. need write:

private sub sleeptimercallback(sender object, e elapsedeventargs) handles _timer.elapsed     try         ' todo need find way bring method on main thread.                 ' re-enable timer elapsed event.         _timer.start()     end end sub 

and you'll want handle exceptions in there, too. otherwise you'll never know occur.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -