ManualResetEvent 基本上对其他线程说“只有在收到继续信号时才能继续”,并用于暂停某些线程的执行,直到满足某些条件。我想问的是,当我们可以通过使用while循环轻松实现我们想要的东西时,为什么ManualResetEvent?考虑以下上下文:
public class BackgroundService {
ManualResetEvent mre;
public BackgroundService() {
mre = new ManualResetEvent(false);
}
public void Initialize() {
// Initialization
mre.Set();
}
public void Start() {
mre.WaitOne();
// The rest of execution
}
}
有点类似于
public class BackgroundService {
bool hasInitialized;
public BackgroundService() {
}
public void Initialize() {
// Initialization
hasInitialized = true;
}
public void Start() {
while (!hasInitialized)
Thread.Sleep(100);
// The rest of execution
}
}
是否有任何特定的上下文ManualResetEvent 比while 循环更合适?