ESD
ESD

Reputation: 545

How to wait for the thread to end before continuing with the program

I have this simple program using threads in C#. How can I make sure that all the threads are done executing before I do a Console.ReadKey(); to terminate the program (else it goes straight to the ReadKey and I have to press it for the threads to keep executing)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Partie_3
{
    class Program
    {
        static int _intToManipulate;
        static object _lock;
        static Thread thread1;
        static Thread thread2;

        static void Main(string[] args)
        {
            _intToManipulate = 0;

            _lock = new object();

            thread1 = new Thread(increment);
            thread2 = new Thread(decrement);

            thread1.Start();
            thread2.Start();

            Console.WriteLine("Done");
            Console.ReadKey(true);
        }



        static void increment()
        {
            lock (_lock)
            {
                _intToManipulate++;
                Console.WriteLine("increment : " + _intToManipulate);
            }
        }
        static void decrement()
        {
            lock (_lock)
            {
                _intToManipulate--;
                Console.WriteLine("decrement : " + _intToManipulate);
            }
        }
    }
}

Upvotes: 0

Views: 265

Answers (2)

JoshVarty
JoshVarty

Reputation: 9426

A similar question can be found here: C#: Waiting for all threads to complete

With C# 4.0+ I personally prefer to use Tasks instead of Threads and wait for them to complete as mentioned in the second highest voted answer:

for (int i = 0; i < N; i++)
{
     tasks[i] = Task.Factory.StartNew(() =>
     {               
          DoThreadStuff(localData);
     });
}
while (tasks.Any(t => !t.IsCompleted)) { } //spin wait

Console.WriteLine("All my threads/tasks have completed. Ready to continue");

If you've got little experience with Threads and Tasks, I'd recommend going down the Tasks route. Comparitively, they're really simple to use.

Upvotes: 3

Patrick Quirk
Patrick Quirk

Reputation: 23747

You're looking for Thread.Join():

thread1.Start();
thread2.Start();

thread1.Join();
thread2.Join();

Console.WriteLine("Done");
Console.ReadKey(true);

Upvotes: 3

Related Questions