ManualResetEvent basically says to other threads "you can only proceed when you receive a signal to continue" and is used to pause execution for certain threads until certain condition has been fulfilled. What I want to ask is that why ManualResetEvent when we could easily achieve what we want by using a while loop? Consider the following context:
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
}
}
is somewhat similar to
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
}
}
Is there any particular context where ManualResetEvent is more suitable than a while loop?