c# - How to synchronize event handlers -


multithreading still on to-do list, title totally wrong :)

my object listening serial port, this:

class myclass {     myopticalscanner _scanner;      public myclass()     {         _scanner = new myopticalscanner();         _scanner.codescanned += codescannedeventhandler;     }      private void codescannedeventhandler(object sender, codescannedeventargs e)     {         debug.writeline("threadid: " + thread.currentthread.managedthreadid + " ||| " + e.scannedcode);         ....         // code, query database, etc...     } } 

the scanner sending ordered data: 001, 002, 003, 004, 005, ... if code in codescannedeventhandler takes long process, event raised , got inconsistent ordering. debug.writeline in event handler give me this:

threadid: 8 ||| 001 threadid: 9 ||| 002 threadid: 10 ||| 003 threadid: 10 ||| 006 threadid: 8 ||| 004 threadid: 8 ||| 008 threadid: 8 ||| 009 threadid: 8 ||| 010 threadid: 10 ||| 007 threadid: 9 ||| 005 

how can assure, each new event starts process when old 1 finished?

edit 1 - didn't told everything, actualy not listening com port during testing, instead created own mock object. object (scannermock) uses internal system.timer , raises codescanned event on timer.ontick event. problem here?

from comment in hans passant's answer: serialport has internal lock ensures datareceived event cannot called again while running. should include similar lock in mocking scanner , how?

edit 2: added lock scanner object , put code, raises event, it. looks works :)

you've got pretty big problem if codescannedeventhandler runs again before previous 1 has finished running. serialport not btw, datareceived event serialized. lock cannot reliably solve problem, order in threads acquire lock isn't guaranteed. see happening, there's lock inside debug.writeline().

if sequence important can keep event handler short , snappy possible takes less time rate @ events run. store scan result in thread-safe queue , out. need thread empties queue. still not 100% guarantee, you'll need whomever wrote myopticalscanner guarantee.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -