SignalAndWait for blocking-context

I have a manager class that creates tasks for the threadpool and each thread has to make a callback upon completion.

I use locks to handle variables and fields, and signals to handle cross messages. What I'm looking for is exiting the current lock () and waiting for a signal atomically, like SignalAndWait, but for locks ().

The code looks something like this:

// ... part of the scheduler
foreach(WorkTask task in worktasks)
{
   lock(_syncObj)
   {
      new Job(task, myCallback); // creates a thread
      instanceCount++;
      while(instanceCount > _maxConcurrentTasks)
          _resetEvent.WaitOne(Timeout.Infinite);
   }
}

// .. the callback

void myCallback()
{
    lock(_syncObj)
    {
        instanceCount--;
        _resetEvent.Set();
    }
}

      

The problem is that .WaitOne () does not break out of blocking (), so any thread executing the callback will be blocked.

I had high hopes for WaitOne (Int32, bool exitContext), but this context seems to be related to deletion and other things, not synchronization.

+1


source to share


1 answer


Is there any reason to use event primitives instead Monitor.Wait/Pulse/PulseAll

? Monitor.Wait

atomically releases the lock and waits, taking over the lock until it returns. See my article on the topic for more details .



+3


source







All Articles