Buddy Murphy
Buddy Murphy

Reputation: 57

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

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

Upvotes: 1

Views: 10862

Answers (3)

Grant Thomas
Grant Thomas

Reputation: 45068

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.

Upvotes: 2

feralin
feralin

Reputation: 3408

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

Upvotes: 1

RandomUs1r
RandomUs1r

Reputation: 4188

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.

Upvotes: 0

Related Questions