即使控制台应用程序退出,也可以保持线程活动

编程入门 行业动态 更新时间:2024-10-21 13:28:03
本文介绍了即使控制台应用程序退出,也可以保持线程活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在C#中有一个控制台应用程序,它可以无限运行,看起来像这样:

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

当线程位于DoWork中时,它正在处理数据,对其进行修改并进行存储.该应用程序等待所有操作完成,然后再次进行新的迭代.

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.

现在,如果关闭了控制台应用程序,则线程似乎无法完成其工作并因控制台应用程序而终止.我认为用Parallel创建的线程独立于主线程.即使我退出控制台应用程序,也可以使线程完成其工作吗?我应该使用不同于Parallel的其他东西来创建线程吗?

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?

推荐答案

关闭窗口后,控制台应用程序将终止所有线程.总是.没有办法解决.控制台窗口直接链接到该过程.

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.

您可能希望使用Windows应用程序,您将对主应用程序循环有更精细的控制.这可能是Windows Service或WinForm/WPF类型的应用程序(如果您不需要的话,甚至不必真正拥有UI).

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

如果您希望Windows应用程序仍然显示控制台-这有点奇怪,但是您可以找到有关如何执行此操作的示例这里.

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.

更多推荐

即使控制台应用程序退出,也可以保持线程活动

本文发布于:2023-11-27 08:27:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1637281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   线程   应用程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!