简体   繁体   中英

C# locking in one thread, calling to releasing in another thread

My scenario:

  • a few BackgroundWorkers to perform various functions.
  • one of them, and only once, will have to execute to do a special work first before continue and letting other works to do their job.

I'm using Monitor.TryEnter : do this special work when it's true (locking is successful); when it's false, will wait for the lock to be released.

Problem is that this special work is done asynchronously. I have a listener, and the CompletedSpecialWork method will be called, but the Thread is different from the Thread where Monitor.TryEnter was performed (that is, the Thread holding(locking) the object). I need a way to be able to send a message to the original Thread asking to release the object.

I tried to have a static object of SynchronizationContext , but when I do threadHoldingLock = SynchronizationContext.Current it is null (it is being called from the BackgroundWorker that was able to hold the lock).

My question is: from this CompletedSpecialWork context/thread, how can I send a request to the original thread (holding the lock) to release the lock via Monitor.Exit ? I need like a way to send a Invoke to the original thread with Monitor.Exit on it.

By their very nature synchronization objects like mutexes need to be released from the same thread that acquired a lock on them. It would pretty much make any kind of synchronization a crashy hit&miss affair if this requirement didn't exist and all your threads could just randomly release all locks from all threads.

You should look at Event objects to signal simple pulses between threads.

Try using either ManualResetEvent or AutoResetEvent.
These can be used to block one thread and then (via function call from a running thread into the blocked thread) allow the block to be reset.
They are syntactic sugar on top of a Semaphore but I like the simplified interface. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM