How do I correctly exit/stop/dispose a console application in C#

南笙酒味 提交于 2019-12-11 04:38:46

问题


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...

Here is the sterilized code

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...

Thanks


回答1:


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.

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.




回答2:


You could try adding a using statement around the use of the Mutex. Example:

using (Mutex mutex = new Mutex(true, "AnalyticsAggregator", out onlyInstance))
{
    if (!onlyInstance) return;
    ... database stuff ...
}

This will automatically dispose of the Mutex instance when the code inside the curly brackets exits by any means (normal execution, or an exception).




回答3:


Application.Exit();

Is the standard approach, however unless you're looking to exit the app through user input (ex. Do you want to quit the app (y/n)?), closing the console should prove sufficient.



来源:https://stackoverflow.com/questions/15619668/how-do-i-correctly-exit-stop-dispose-a-console-application-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!