Oriol
Oriol

Reputation: 61

Keep threads alive even if console app exits

I have a console app in C# that runs endlessly and looks something like this:

class Program
{
    static void Main(string[] args)
    {    
        while(true)
        {
            var listOfIds = GetItemIds();
            Parallel.ForEach(listOfIds,
                new Parallel { MaxDegreeOfParallelism = 15}, th => DoWork(th));
            Console.WriteLine("Iteration Complete");
        }
    }

    static void DoWork(int id)
    {
        //do some work and save data
    }

    static List<int> GetItemIds()
    {
        //return a list of ints
    }       
}

While a thread is in DoWork, it is processing data, modifying it and storing it. The app waits for all to finish and then goes again for a new iteration.

Now, if the console app is closed, it seems that threads do not finish their work and die with the console app. I thought threads created with Parallel were independent of the main thread. Is there a way to make the threads finish their work even if I exit the console app? should I use something different rather than Parallel to create the threads?

Upvotes: 3

Views: 1718

Answers (1)

TheSoftwareJedi
TheSoftwareJedi

Reputation: 35196

A console app is going to kill all threads when the window is closed. Always. There is no way around that. The console window is directly linked to the process.

You may wish to use a Windows application which you will have more fine grained control over the main application loop. This could be a Windows Service or a WinForm/WPF type of application (which doesn't even really have to have a UI if you don't want).

If you want a Windows Application that still shows the console - this is a bit wonky, but you can find an example of how to do that here.

Upvotes: 3

Related Questions