0

I have a typical Producer/Consumer problem and trying to synchronize 2 Threads. I want to find an alternative to Suspend() and Resume() in C# Compact Framework. They both arent supported by CF :( . I found some examples, which are based on EventWaitHandle and use something like :

      private EventWaitHandle ewh = new AutoResetEvent();

But the problem is that also AutoResetEvent isnt a part of Compact Framework. I would like to know whether there is an another way of solving such Producer/Consumer troubles using EventWaitHandle. I know that AutoResetEvent is derived from EventWaitHandle. Which other Subclasses of EventWaitHAndle do you know?

JoelC
  • 3,664
  • 9
  • 33
  • 38
  • 1
    The Monitor class is the Swiss army knife of synchronization. Lots of google hits for ".net monitor producer consumer algorithm", don't invent your own. – Hans Passant Nov 06 '14 at 17:40

2 Answers2

1

As you found, there is no autoreset event. But you can workaround using pinvoke to CreateEvent and WaitForSingleObject etc. Or, if you simple want to sync the access to an object, simply use Lock with an 'Lock' object. The use is in pseudo code:

thread1 while(true){ Lock(myLockObject){ access the shared object(s) } Thread.Sleep(1000) }

thread2 while(true){ Lock(myLockObject){ access the shared object(s) } Thread.Sleep(1100) }

Each thread will lock the same object and only one thread at a time can access the shared objects. The code inside the lock will only run if the lock object is not locked by another code line (here by another thread). You may simply use this to 'Suspend' and resume a thread. The Lock object was designed to enable synchronized access to a shared var.

OTOH, as already mentioned, just pinvoke the native CreateEvent, WaitForSingleObject, SetEvent API functions.

josef
  • 5,951
  • 1
  • 13
  • 24
0

I must apologize, there is indeed AutoResetEvent in Compact Framework. Thank to Hans Passant who suggested to use Monitor class for synchronization.