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