如何保持一个.NET控制台应用程序运行? [英] How to keep a .NET console app running?

查看:182
本文介绍了如何保持一个.NET控制台应用程序运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到在单独的线程启动一些服务控制台应用程序。它所需要做的是等待用户preSS Ctrl + C键将其关闭。

以下哪个是更好的方式来做到这一点?

 静态的ManualResetEvent _quitEvent =新的ManualResetEvent(假);静态无效的主要(){
    Console.CancelKey preSS + =(发件人,eArgs)=> {
        _quitEvent.Set();
        eArgs.Cancel =真;
    };    //开球异步的东西    _quitEvent.WaitOne();    //清理/关闭并退出
}

还是这个,使用Thread.sleep代码(1):

 静态布尔_quitFlag = FALSE;静态无效的主要(){
    Console.CancelKey preSS + = {委托
        _quitFlag = TRUE;
    };    //开球异步的东西    而(!_quitFlag){
        Thread.sleep代码(1);
    }    //清理/关闭并退出
}


解决方案

在使用whil​​e循环总是要prevent,尤其是当你正迫使code重新检查变量。它浪费了CPU资源,减慢你的程序。

我肯定会说的第一个。

Consider a Console application that starts up some services in a separate thread. All it needs to do is wait for the user to press Ctrl+C to shut it down.

Which of the following is the better way to do this?

static ManualResetEvent _quitEvent = new ManualResetEvent(false);

static void Main() {
    Console.CancelKeyPress += (sender, eArgs) => {
        _quitEvent.Set();
        eArgs.Cancel = true;
    };

    // kick off asynchronous stuff 

    _quitEvent.WaitOne();

    // cleanup/shutdown and quit
}

Or this, using Thread.Sleep(1):

static bool _quitFlag = false;

static void Main() {
    Console.CancelKeyPress += delegate {
        _quitFlag = true;
    };

    // kick off asynchronous stuff 

    while (!_quitFlag) {
        Thread.Sleep(1);
    }

    // cleanup/shutdown and quit
}

解决方案

you always want to prevent using while loops, especially when you are forcing the code to recheck variables. It wastes CPU resources and slows down your program.

I would definitely say the first one.

这篇关于如何保持一个.NET控制台应用程序运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆