开发者

C# .Net 4.0 Console App - how to stay alive until all threads complete? [duplicate]

开发者 https://www.devze.com 2023-03-03 10:07 出处:网络
This question already has answers here: 开发者_JAVA技巧 Closed 10 years ago. Possible Duplicate: C#: Waiting for all threads to complete
This question already has answers here: 开发者_JAVA技巧 Closed 10 years ago.

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?


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


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


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.


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


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消