does Monitor.Wait Needs synchronization?

前端 未结 3 924
予麋鹿
予麋鹿 2020-12-11 17:05

I have developed a generic producer-consumer queue which pulses by Monitor in the following way:

the enqueue :

    public void EnqueueTask(T task)
           


        
3条回答
  •  一个人的身影
    2020-12-11 18:03

    Yes, the current thread needs to "own" the monitor in order to call either Wait or Pulse, as documented. (So you'll need to lock for Pulse as well.) I don't know the details for why it's required, but it's the same in Java. I've usually found I'd want to do that anyway though, to make the calling code clean.

    Note that Wait releases the monitor itself, then waits for the Pulse, then reacquires the monitor before returning.

    As for using ManualResetEvent or AutoResetEvent instead - you could, but personally I prefer using the Monitor methods unless I need some of the other features of wait handles (such as atomically waiting for any/all of multiple handles).

提交回复
热议问题