I got confused why when I used task the time of stopwatch will display but when I used thread it will not. What’s wrong with my code? Am i missing something?
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
//if I used this sw.Elapsed will display
//Task t1 = Task.Factory.StartNew(runTask1);
//Task t2 = Task.Factory.StartNew(runTask2);
//Task.WaitAll(t1, t2);
//if I used this sw.Elapsed will not display
//Thread t1 = new Thread(runTask1);
//Thread t2 = new Thread(runTask2);
//t1.Start();
//t2.Start();
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadLine();
}
public static void runTask1()
{
for (int x = 1; x <= 5000; x++)
{
Console.WriteLine("Run task tester 1");
}
}
public static void runTask2()
{
for (int x = 1; x <= 5000; x++)
{
Console.WriteLine("Run task tester 2");
}
}
When you’re using tasks, you wait for them to complete their work before stopping the stopwatch and displaying the time. When you’re using threads you don’t wait for them to finish before displaying the result therefore it is printed at the top above the text from the threads.
You want to wait for the threads to finish as well: