Keep threads alive even if console app exits

筅森魡賤 提交于 2020-05-15 10:36:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/52722920/keep-threads-alive-even-if-console-app-exits

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