如何正确退出/停止/处置C#中的控制台应用程序 [英] How do I correctly exit/stop/dispose a console application in C#

查看:668
本文介绍了如何正确退出/停止/处置C#中的控制台应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任务管理器中注意到我有该应用程序的多个副本-尽管没有占用任何CPU资源。

I noticed in my Task Manager I have several copies of this app - though not take any CPU resources.

我知道我一定做错了,所以我问集体...

I know I must be doing something wrong, so I ask the collective...

这是经过消毒的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace AnalyticsAggregator
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        try
        {
            bool onlyInstance = false;
            Mutex mutex = new Mutex(true, "AnalyticsAggregator", out onlyInstance);
            if (!onlyInstance)
            {
                return;
            }

                            "Do stuff with the database"


            GC.KeepAlive(mutex);
        }
        catch (Exception e)
        {

                EventLog eventlog = new EventLog("Application");
                eventlog.Source = "AnalyticsAggregator";
                eventlog.WriteEntry(e.Message, EventLogEntryType.Error);
            }
        }
    }
}
}

我还有其他非互斥/单一控制台应用程序,它们表现出相同的行为,我在做什么错?我假设某种处置方式...

I have other console apps that are not mutex/singleton that exhibit the same behavior, what am I doing wrong? I am assuming some type of disposal...

谢谢

推荐答案

控制台应用程序完成后通常会终止,通常是运行到其 Main 入口点方法的末尾,尽管您必须小心摆脱任何挥之不去的资源您可能一直在进行管理,因为它们可以使基础流程保持活动状态。

A console application will just terminate when it's done, generally when it runs to the end of its Main entry point method, though you must be careful to get rid of any lingering resources you might have been managing, as they can keep the underlying process alive.

您可以使用 Environment.Exit ,以及 Application.Exit ,尽管后者根据我的经验是基于表单的(与清除消息泵和关闭窗口等有关)。

You can explicitly exit using Environment.Exit, and also Application.Exit although the latter is Forms-based from my experience (relating to clearing message pumps and closing windows etc.).

最重要的是确保做家务。

Bottom line is to be sure to do housekeeping.

这篇关于如何正确退出/停止/处置C#中的控制台应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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