What is the difference between ManualResetEvent and AutoResetEvent in .NET?

后端 未结 11 2203
慢半拍i
慢半拍i 2020-11-27 09:06

I have read the documentation on this and I think I understand. An AutoResetEvent resets when the code passes through event.WaitOne(), but a ManualResetEvent do

11条回答
  •  渐次进展
    2020-11-27 09:28

    Taken from C# 3.0 Nutshell book, by Joseph Albahari

    Threading in C# - Free E-Book

    A ManualResetEvent is a variation on AutoResetEvent. It differs in that it doesn't automatically reset after a thread is let through on a WaitOne call, and so functions like a gate: calling Set opens the gate, allowing any number of threads that WaitOne at the gate through; calling Reset closes the gate, causing, potentially, a queue of waiters to accumulate until its next opened.

    One could simulate this functionality with a boolean "gateOpen" field (declared with the volatile keyword) in combination with "spin-sleeping" – repeatedly checking the flag, and then sleeping for a short period of time.

    ManualResetEvents are sometimes used to signal that a particular operation is complete, or that a thread's completed initialization and is ready to perform work.

提交回复
热议问题