[英]C# locking in one thread, calling to releasing in another thread
My scenario:我的场景:
BackgroundWorkers
to perform various functions.BackgroundWorkers
来执行各种功能。 I'm using Monitor.TryEnter
: do this special work when it's true (locking is successful);我正在使用
Monitor.TryEnter
:当它为真时做这个特殊的工作(锁定成功); 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).我有一个监听器,会调用
CompletedSpecialWork
方法,但 Thread 与执行Monitor.TryEnter
的 Thread 不同(即持有(锁定)对象的 Thread)。 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).我试图拥有
SynchronizationContext
的静态对象,但是当我执行threadHoldingLock = SynchronizationContext.Current
它为空(它是从能够保持锁定的 BackgroundWorker 调用的)。
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
?我的问题是:从这个
CompletedSpecialWork
上下文/线程,我如何向原始线程(持有锁)发送请求以通过Monitor.Exit
释放锁? I need like a way to send a Invoke to the original thread with Monitor.Exit on it.我需要一种将 Invoke 发送到带有 Monitor.Exit 的原始线程的方法。
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.您应该查看 Event 对象以在线程之间发出简单的脉冲信号。
Try using either ManualResetEvent or AutoResetEvent.尝试使用 ManualResetEvent 或 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!
祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.