views:

21

answers:

2

I'm struggling with an event related to my communications class.

I'm calling a 'DataChange' function via event handler any time I receive new data over my serial connection. I then proceed to load that data into a DataGridView, perform some formatting, etc for the users. I'm getting a ton of problems due to the frequency at which the DataChange event is called and seems to steal the focus out of othert subroutines and functions mid-process.

For example, I'll attempt to transmit data back to the serial device. After I format the data, but before I can actually call the Send function from my library the focus is directed back to DataChange and I never actually transmit my data.

Is this a problem best addressed by threading the DataChange related routines, unhooking the DataChange event before a function or routine then rehooking, or is there some basic principle I'm not implementing.

+1  A: 

This sounds like it could potentially be a thread synchronization issue.

Events are inherently threaded, so addressing it by adding threading is not an issue.

Try using SyncLock to ensure thread synchronization.

Whenever you receive data, lock an object until you're finished using the data.

SyncLock lockObject
    'Handle data changed...
End SyncLock

I believe the term for this situation is a race condition.

Aequitarum Custos
A: 

Have your data come into a buffer on one thread and watch the buffer from another thread. On the primary thread flag the buffer as "ready-to-send" and have the secondary thread watch for that. Just make sure to SyncLock the object. Depending on what your data is, you can create an object to wrap it maybe and just use a boolean flag and then dump that into a List(Of T). Have your monitor thread Sleep for 50 or whatever milliseconds, lock the buffer and check for flags, pull out what's needed, unlock the list and push the data out.

Chris Haas