Monitor.Enter
和 Monitor.Exit
的设计是从同一个线程调用。但是,如果我需要什么比获得在不同的线程释放锁?
Monitor.Enter
and Monitor.Exit
are designed to be called from the same thread. But, what if I need to release a lock in a different thread than acquired?
例如:有共享使用该资源的资源和异步操作。操作以 BeginOperation
并获得共享资源的锁定。此外,还有的 EndOperation
方法释放锁。 EndOperation
通常被称为从回调另一个线程,因此我不能叫 Monitor.Exit
在 EndOperation
方法。什么是在这种情况下,最好的方法?将与的AutoResetEvent
仔细检查锁定,而不是显示器
是一个很好的解决办法吗?
For example: there are shared resource and asynchronous operation that uses this resource. The operation begins with BeginOperation
and acquires the lock on the shared resource. There also the EndOperation
method that releases the lock. EndOperation
is typically called in another thread from a callback, thus I can't call Monitor.Exit
in the EndOperation
method. What is the best approach in this case? Will double-check locking with AutoResetEvent
instead of Monitor
be a good solution?
尝试使用ManualResetEvent的,它是用来阻止THEAD(S),直到一些外部事件被触发。 MSDN文档:
Try using a ManualResetEvent, it's used to block thead(s) until some external event has been triggered. MSDN Doc:
的http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx