【发布时间】:2013-12-09 06:50:23
【问题描述】:
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 循环更合适?
【问题讨论】:
-
ManualResetEvent更准确。在最坏的情况下,您的循环可能会浪费 99 毫秒。 -
线程在 while 循环中是相同的,因为它实际上无法执行任何其他工作,就像您有多个线程一样,可能存在某些区域可能需要一些指示继续做下一个线程做的事情,例如,可能是批处理结果,其中 T1 对它们进行批处理,引发一个信号,然后 T2 可能正在执行批处理的批处理插入/处理。这只是一个例子——每个线程都致力于做某事。单个线程不会那么多,性能和可维护性可能会很慢
-
如何使用while循环实现线程同步?使用手动重置事件很简单直接。您还需要从我认为的设计角度考虑哪种结构适合您的需求。
标签: c# manualresetevent