0

I have an application where a thread is used to calculate a bunch of numbers but the problem is that the application finishes before the Thread completes the calculation and returns the calculated number. What's the way of making the application wait until the calculation is done?

Here's my code:

namespace ThreadWaiting
{
    class Program
    {
        public static int number=0;

        public static void Main(string[] args)
        {
            Thread t = new Thread(Calculate);
            t.Start();

            //Wait here until processed?

            Console.WriteLine(number);
            Console.ReadKey();
        }

        private static void Calculate(object obj)
        {
            number = 2 + 2;
        }
    }
}

If you run that, you will see that it prints "0" and not "4".

Any ideas guys? Thanks!

PewK
  • 397
  • 3
  • 8
  • 19

1 Answers1

2

To wait until a thread is done, you Join it:

t.Join();
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • I should add this below the t.Start() ? – PewK Oct 10 '14 at 12:50
  • If you want to wait for the thread at this point, then yes. Starting a thread just to wait for it doesn't make a lot of sense though. – nvoigt Oct 10 '14 at 12:51
  • Hmmm then what's the best way to Process an output in a thread and retrieve it? – PewK Oct 10 '14 at 12:53
  • Why do you want a thread? The whole point of a thread is that you can do stuff while it's running. – nvoigt Oct 10 '14 at 12:59
  • To make things efficient and faster. My Thread handles a method that does a lot of heavy calculations in my original Project. But the Calculations need to be returned to the main UI and thus this problem. But the Join solved it. Is there a better way sir? – PewK Oct 10 '14 at 13:01
  • If you Join on another thread in your UI, you will be back to step one because you will have blocked your GUI. But if you solved your problem, then everything is fine. – nvoigt Oct 10 '14 at 13:15