写一个无限循环很简单:
while(true){
//add whatever break condition here
}
但这会降低 CPU 性能。该执行线程将尽可能多地占用 CPU 的资源。
降低对 CPU 影响的最佳方法是什么?
添加一些 Thread.Sleep(n)
应该可以解决问题,但是为 Sleep()
方法设置高超时值可能表明应用程序对操作系统没有响应。
假设我需要在控制台应用程序中每分钟左右执行一次任务。
我需要让 Main()
在“无限循环”中运行,而计时器将触发完成该工作的事件。我希望 Main()
对 CPU 的影响最小。
你有什么建议。 Sleep()
可能没问题,但正如我已经提到的,这可能表明线程对操作系统没有响应。
后期编辑:
我想更好地解释我在寻找什么:
我需要一个控制台应用程序,而不是 Windows 服务。控制台应用程序可以在带有 Compact Framework 的 Windows Mobile 6.x 系统上模拟 Windows 服务。
我需要一种方法,只要 Windows Mobile 设备在运行,应用程序就会一直运行。
我们都知道,只要控制台应用程序的静态 Main() 函数运行,它就会一直运行,因此我需要一种方法来防止 Main() 函数退出。
在特殊情况下(例如:更新应用程序),我需要请求应用程序停止,因此我需要无限循环并测试某些退出条件。例如,这就是为什么
Console.ReadLine()
对我没用。没有退出条件检查。关于上述内容,我仍然希望 Main() 函数尽可能资源友好。撇开检查退出条件的函数的指纹。
最佳答案
要避免无限循环,只需使用 WaitHandle
。要让进程从外部世界退出,请使用具有唯一字符串的 EventWaitHandle
。下面是一个例子。
如果您是第一次启动它,它会每 10 秒打印一条消息。如果您同时启动该程序的第二个实例,它将通知其他进程正常退出并立即退出。这种方法的 CPU 使用率:0%
private static void Main(string[] args)
{
// Create a IPC wait handle with a unique identifier.
bool createdNew;
var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "CF2D4313-33DE-489D-9721-6AFF69841DEA", out createdNew);
var signaled = false;
// If the handle was already there, inform the other process to exit itself.
// Afterwards we'll also die.
if (!createdNew)
{
Log("Inform other process to stop.");
waitHandle.Set();
Log("Informer exited.");
return;
}
// Start a another thread that does something every 10 seconds.
var timer = new Timer(OnTimerElapsed, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
// Wait if someone tells us to die or do every five seconds something else.
do
{
signaled = waitHandle.WaitOne(TimeSpan.FromSeconds(5));
// ToDo: Something else if desired.
} while (!signaled);
// The above loop with an interceptor could also be replaced by an endless waiter
//waitHandle.WaitOne();
Log("Got signal to kill myself.");
}
private static void Log(string message)
{
Console.WriteLine(DateTime.Now + ": " + message);
}
private static void OnTimerElapsed(object state)
{
Log("Timer elapsed.");
}
关于c# - CPU友好的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7402146/