What is the lifecycle, if any, of c# executable console application?

c#, console-application

Solution

Normally, each method is JITted as it is first executed, with assembly resolution again happening as-needed, which usually means "during JIT of a method that uses an assembly we haven't needed yet" (but can also mean: via reflection).

`static Main` works the same as any other method; anything you use in `Main` will be resolved before `Main` starts executing. In some cases you might want (to help debugging):

static int Main(string[] args) {
    try {
        return MainImpl(args);
    } catch(Exception ex) {
        // .. do something
        return -1;
    }
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int MainImpl(string[] args) { ... }

This is useful if the code that would normally be in `Main` (but is now in `MainImpl`) is causing assembly resolution errors... since you can't `catch` something in `Main` if `Main` can't first be JITted successfully.

As for life-cycle...

- the entry-point is started (`Main`)

- the application exits when no non-background threads are alive; for a typical linear console exe that means "when `Main` exits", but can be more complex in a threaded server example

- or it can be terminated prematurely from within or from outside

Problem

I am interested to find out if there is any sort of life-cycle of a C# console application, similar to the ASP.Net life-cycle. I am particularly interested in - assembly resolution - when does this happen - compilation - how does the `static Main` method affect compilation of dependant objects

Original source