Quick Quiz on Tasks

Fri, August 22, 2008, 07:26 PM under ParallelComputing
Steps:
1. New C# Console Project in VS2008
2. Add Reference to System.Threading.dll (from Parallel Extensions June CTP)
3. Replace the entire contents of Program.cs with the following (overly simplified extract of a more complex piece of code):
using System;
using System.Threading.Tasks;

static class Program
{
static void Main()
{
Task t1 = Task.Create(delegate
{
Task t2 = Task.Create( // breakpoint #1
(o) =>
Console.WriteLine(o.ToString()) // breakpoint #2
, "hey");
t2.Wait(); // breakpoint #3
});
t1.Wait(); // breakpoint #4

Console.ReadLine(); // breakpoint #5
}
}

4. Insert a breakpoint (F9) wherever there is a comment.

Questions:
A. Without running the project, what can you predict about which breakpoints will be hit and in what order?
B. Can you predict at each breakpoint, which of the two variables (t1, t2) is in scope (e.g. if they were in the Watch window)?
Friday, 22 August 2008 21:53:00 (Pacific Daylight Time, UTC-07:00)
Sure, I'll take a stab at it:

A. (ordering breakpoints from top to bottom as BP1-BP5)

BP4 should get hit first since there is overhead in creating (and starting) t1
BP1 would be next
BP3 would get hit next since there is overhead in creating (and starting) t2
BP2 would be next, causing the Wait() at BP3 to cause t1 to finish, letting t1 finish as well, so
BP5 finally

B. t1 or t2 in scope?
BP1 t1, t2
BP2 t1, t2
BP3 t1, t2
BP4 t1
BP5 t1

o will be "hey". How'd I do? (goes and tries it)
Saturday, 23 August 2008 15:00:00 (Pacific Daylight Time, UTC-07:00)
if we numbered them top to bottom I would say it would stop in the following sequence:

5, 4, 1, 3, 2
Saturday, 06 September 2008 16:20:00 (Pacific Daylight Time, UTC-07:00)
4,1,3,2,5
Friday, 19 September 2008 00:57:37 (Pacific Daylight Time, UTC-07:00)
Mattman206, BlackTigerX: Thanks guys. Answers here and here.
Comments are closed.