0

I have some difficulties designing the way my code should work:

  1. Serial #1 (receives data at any time) invokes Routine() if some particular received value A is > constant1, but only if Routine() is not running, otherwise ONLY the last invocation will run after Routine() ends
  2. Serial #2 (receives data at any time) sets B and C with the received data
  3. Routine() checks if C > constant2 and saves B and C to a file
  4. Timer (every N seconds) runs another routine that checks the saved files and sends an email (without interfering with Routine() while is saving B and C)

My current design uses a couple of global booleans, but I think that is producing some problems (due the boolean changing between checking it and setting it again to start the 'locked' procedure).

So, what is the recommended way to take down a sync problem like this? lock(someGlobalObject)?, using Monitor? (how I discard multiple pending routine() invocations?), Mutex?, Semaphore?

Thanks!

eried
  • 398
  • 5
  • 15

1 Answers1

0

First off, lock and Monitor are functionally the same.
Lock statement vs Monitor.Enter method

Now, generally, when I'm writing multi-threaded code, the decision is between either a ReaderWriterLock (ReaderWriterLockSlim if on .NET 3.5 or later) and lock(). lock() will perform better when you have multiple threads that need to write to the same object and few that need to read. ReaderWriterLocks will perform better when you have concurrent data that is read much more frequently (and from multiple threads) than it is written to.

ReaderWriterLock vs lock{}

If I understand your example correctly, B and C are objects that are accessed from multiple threads. It looks like they are written to from one thread and read from two other threads. So, I would suggest that it all depends on the frequency of the reads and writes. If B and C are written to much more frequently than they are read, try a lock() statement. Otherwise, if they are read more frequently, go with a ReaderWriterLock(Slim) object. Obviously, you'll need to run some tests to determine if one is better than the other. Either one should solve the problem, though one is most likely going to be faster than the other.

Community
  • 1
  • 1
Wyatt Earp
  • 1,783
  • 13
  • 23