0

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);
            }
        }
    }
}
Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
ESD
  • 675
  • 2
  • 12
  • 35

2 Answers2

3

You're looking for Thread.Join():

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

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

Console.WriteLine("Done");
Console.ReadKey(true);
Patrick Quirk
  • 23,334
  • 2
  • 57
  • 88
  • 3
    That said, it's probably a lot wiser to be using the TPL instead of manually mucking about with `Thread` objects. – Daniel Mann Nov 04 '12 at 18:02
3

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.

Community
  • 1
  • 1
JoshVarty
  • 9,066
  • 4
  • 52
  • 80