C# 多线程控制台应用程序 - 控制台在线程完成之前退出 [英] C# multi-threaded console application - Console quits before threads complete

查看:102
本文介绍了C# 多线程控制台应用程序 - 控制台在线程完成之前退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最多可创建 5 个线程的 c# 控制台应用程序.

I have a c# console application that creates up to 5 threads.

线程运行良好,但 UI 线程在完成工作后关闭.

The threads are executing fine, but the UI thread shuts down as it finishes its work.

有没有办法让主 UI 线程一直运行,只要侧线程正在运行?

Is there a way to keep the main UI thread running, for as long as the side threads are running?

foreach (var url in urls)
{
    Console.WriteLine("starting thread: " + url); 
    ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myMethod), url);
}

我正在按照上面的代码启动我的线程.

I'm kicking off my threads as per the code above.

推荐答案

ThreadPool 中的线程是后台线程,这意味着退出的应用程序不会等待它们完成.

The threads in the ThreadPool are background threads and that means an exiting application won't wait for them to complete.

您有几个选择:

  • 等待例如信号量
  • 使用 Sleep() 等待计数器,非常粗糙,但对于简单的控制台应用程序来说还可以.
  • 使用 TPL,Parallel.ForEach(urls, url => MyMethod(url));

这篇关于C# 多线程控制台应用程序 - 控制台在线程完成之前退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆