Quick Quiz on Tasks

Fri, August 22, 2008, 07:26 PM under ParallelComputing
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.

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, August 22, 2008 9:53:00 PM (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, August 23, 2008 3:00:00 PM (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, September 6, 2008 4:20:00 PM (Pacific Daylight Time, UTC-07:00)
Friday, September 19, 2008 12:57:37 AM (Pacific Daylight Time, UTC-07:00)
Mattman206, BlackTigerX: Thanks guys. Answers here and here.
Comments are closed.