I've used a thread managed waiter.
SyncLock http://msdn.microsoft.com/en-us/library/3a86s51t%28v=vs.71%29.aspx
But now, I wanted to have a timeout and fo开发者_JS百科und the WaitOne.
WaitOne http://msdn.microsoft.com/en-us/library/system.threading.waithandle.waitone.aspx which supports a simple timeout.
But it does not work anymore. It can be that the fault is somewhere else in the code. My main question to you is, is there a difference between using SyncLock
and WaitOne
as basic waiter flag?
Regards
SyncLock
is a language specific wrapper for Monitor.Enter
and Monitor.Exit
. It is intended to be used to restrict simultaneously access to a critical section of code or resource.
WaitHandle.WaitOne
is a method that is intended to be used in scenarios where a thread should wait for an external signal. The exact implementation and semantics of how it works is class specific. In other words, WaitOne
will behave differently when used from an AutoResetEvent
as compared to a ManualResetEvent
or Semaphore
.
The two are really targeted for different use cases. Without a better description of your specific problem it is difficult to even speculate which one is best to use.
However, if you know for certain that you want the semantics of a lock (via SyncLock
or the Monitor
class) then you can use Monitor.TryEnter
which does provide a timeout parameter.
From MSDN http://msdn.microsoft.com/en-us/library/ms173179.aspx
Using a lock or monitor is useful for preventing the simultaneous execution of thread-sensitive blocks of code, but these constructs do not allow one thread to communicate an event to another. This requires synchronization events, which are objects that have one of two states, signaled and un-signaled, that can be used to activate and suspend threads. Threads can be suspended by being made to wait on a synchronization event that is unsignaled, and can be activated by changing the event state to signaled. If a thread attempts to wait on an event that is already signaled, then the thread continues to execute without delay.
There are two kinds of synchronization events: AutoResetEvent, and ManualResetEvent. They differ only in that AutoResetEvent changes from signaled to unsignaled automatically any time it activates a thread. Conversely, a ManualResetEvent allows any number of threads to be activated by its signaled state, and will only revert to an unsignaled state when its Reset method is called.
Threads can be made to wait on events by calling one of the wait methods, such as WaitOne, WaitAny, or WaitAll. WaitHandle.WaitOne() causes the thread to wait until a single event becomes signaled, WaitHandle.WaitAny() blocks a thread until one or more indicated events become signaled, and WaitHandle.WaitAll() blocks the thread until all of the indicated events become signaled. An event becomes signaled when its Set method is called.
精彩评论