C# .Net 4.0 控制台应用程序 - 如何保持活动状态直到所有线程完成?

发布于 2024-11-05 08:02:13 字数 295 浏览 1 评论 0原文

可能的重复:
C#:等待所有线程完成

我有一个控制台应用程序,产生一些线程然后退出。每个线程大约需要 20 秒才能完成。看起来控制台应用程序正在生成线程,然后在线程有机会完成之前退出。

如何告诉控制台应用程序在其生成的所有线程完成之前不要退出?

Possible Duplicate:
C#: Waiting for all threads to complete

I have a console app that spawns some threads and then exits. Each thread takes roughly ~20 seconds to complete. It appears as though the console app is spawning the threads and then exiting before the threads have a chance to complete.

How do I tell the console app not to exit until all threads it has spawned have completed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

倾城°AllureLove 2024-11-12 08:02:13

您可以使用CountDownEvent

using System;
using System.Collections.Generic;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static CountdownEvent countdown;

        static void Main(string[] args)
        {
            countdown = new CountdownEvent(1);
            for (int i = 1; i < 5; i++)
            {
                countdown.AddCount(); //add a count for each (BEFORE starting thread .. Thanks, Brian!)
                //do stuff to start background thread
            }
            countdown.Signal(); //subtract your initial count
            countdown.Wait(); //wait until countdown reaches zero
            //done!
        }

        static void backgroundwork()
        {
            //work
            countdown.Signal(); //signal this thread's completion (subtract one from count)
        }
    }
}

You can to use a CountDownEvent.

using System;
using System.Collections.Generic;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static CountdownEvent countdown;

        static void Main(string[] args)
        {
            countdown = new CountdownEvent(1);
            for (int i = 1; i < 5; i++)
            {
                countdown.AddCount(); //add a count for each (BEFORE starting thread .. Thanks, Brian!)
                //do stuff to start background thread
            }
            countdown.Signal(); //subtract your initial count
            countdown.Wait(); //wait until countdown reaches zero
            //done!
        }

        static void backgroundwork()
        {
            //work
            countdown.Signal(); //signal this thread's completion (subtract one from count)
        }
    }
}
飘过的浮云 2024-11-12 08:02:13

线程是否会循环生成?如果是这样,Parallel.ForEach 就可以工作:

ParallelOptions options = new ParallelOptions();
                    Parallel.ForEach(items, options, item=>
                    {
// Do Work here
                    });

Are the threads spawned for a loop? If so a Parallel.ForEach would work:

ParallelOptions options = new ParallelOptions();
                    Parallel.ForEach(items, options, item=>
                    {
// Do Work here
                    });
得不到的就毁灭 2024-11-12 08:02:13

只要 Thread 不是后台线程 (.IsBackground),应用程序就应该保持活动状态:

static void Main()
{
    Thread thread = new Thread(MoreStuff);
    thread.IsBackground = false;
    thread.Start();
    Console.WriteLine("Main thread exiting");
}
static void MoreStuff()
{
    Console.WriteLine("Second thread starting");
    Thread.Sleep(5000); // simulate work
    Console.WriteLine("Second thread exiting");
}

不需要其他任何东西。请注意,ThreadPool 将使用后台线程;问题可能是您在这里使用 ThreadPool 吗?

注意:如果第二个线程实际上还没有启动,那么可能会发生一场小竞赛,它可能会提前退出;您可能想要对线程启动进行门控。

As long as the Thread is not a background-thread (.IsBackground), the app should stay alive:

static void Main()
{
    Thread thread = new Thread(MoreStuff);
    thread.IsBackground = false;
    thread.Start();
    Console.WriteLine("Main thread exiting");
}
static void MoreStuff()
{
    Console.WriteLine("Second thread starting");
    Thread.Sleep(5000); // simulate work
    Console.WriteLine("Second thread exiting");
}

Nothing else is needed. Note that the ThreadPool will use background threads; is the problem perhaps that you are using ThreadPool here?

Note: if the second thread hasn't actually started there might be a small race where it can exit prematurely; you might want to gate the threads starting.

懒猫 2024-11-12 08:02:13

您可以使用 Thread.Join 来等待线程完成。

You can use Thread.Join to wait for a thread to complete.

江湖彼岸 2024-11-12 08:02:13

你如何启动线程?这确实取决于,但如果您只是使用 Thread 类,则从主线程调用 yourThread[i].Join() 以确保所有线程完成。

查看任务和任务工厂来处理事情比过去几年干净得多。

How are you launching the threads? It really depends, but if you are just using the Thread class, then call yourThread[i].Join() from the main thread to ensure that all threads complete.

Look into the Tasks and Task Factory to handle things a lot more cleanly than in years past.

看春风乍起 2024-11-12 08:02:13

在启动后启动的所有线程上调用 Thread.Join() 。这将阻塞当前线程,直到线程完成。

Call Thread.Join() on all of the Threads that you start after they have started. This will block the current thread until the thread is complete.

浮生面具三千个 2024-11-12 08:02:13

您可能应该使用同步并等待任何生成的线程完成其工作,方法是通过调用 Thread.Join 来阻止主线程或使用信号发送(例如使用监视器或其他选项之一)。

或者,您可以简单地通过设置 IsForeground 属性 (afaicr) 使生成的线程作为前台线程运行。这将使应用程序保持活动状态,直到线程终止,但您仍然会看到控制台窗口随着主线程退出而消失。

You should probably use synchronization and wait for any spawned threads to complete their work, either by blocking the main thread with calls to Thread.Join or using signalling (e.g. using a Monitor or one of the other options for this).

Alternatively you can simply make the spawned threads run as foreground threads, by setting the IsForeground property (afaicr). This will keep the application alive until the threads have terminated, but you will still see the console window disappear as the main thread exits.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文