CSharp · Console
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
static void DoWork() => Thread.Sleep(100);
static Task X() => Task.Delay(1000);
// Pretty type name, e.g. Task<Task<int>>
static string Name(Type t)
{
if (t == typeof(int)) return "int";
if (!t.IsGenericType) return t.Name;
var args = string.Join(", ", t.GetGenericArguments().Select(Name));
return $"{t.Name.Split('`')[0]}<{args}>";
}
// T is the compile-time type of the variable
static void Show<T>(string label, T value) =>
Console.WriteLine($"{label} {Name(typeof(T))}");
public static async Task Main()
{
var t1 = Task.Factory.StartNew(() => { DoWork(); });
var t2 = Task.Factory.StartNew(() => 42);
var t3 = Task.Factory.StartNew(async () => { await X(); });
var t4 = Task.Factory.StartNew(async () => { await X(); return 42; });
var t5 = Task.Run(() => { DoWork(); });
var t6 = Task.Run(() => 42);
var t7 = Task.Run(async () => { await X(); });
var t8 = Task.Run(async () => { await X(); return 42; });
Show("t1", t1);
Show("t2", t2);
Show("t3", t3); // trap
Show("t4", t4); // trap
Console.WriteLine();
Show("t5", t5);
Show("t6", t6);
Show("t7", t7);
Show("t8", t8);
await Task.WhenAll(t1, t2, t3, t4, t5, t6, t7, t8);
Console.WriteLine("\n--- The trap in action ---");
var sw = Stopwatch.StartNew();
// t3: await only waits for the outer task,
// which completes as soon as the lambda hits its first await.
var a = Task.Factory.StartNew(async () => { await X(); });
await a;
Console.WriteLine($"[{sw.Elapsed.TotalSeconds:0.0}s] await t3 finished (X() is still running!)");
// t4: a single await gives Task<int>, not int
var b = Task.Factory.StartNew(async () => { await X(); return 42; });
Task<int> inner = await b;
Console.WriteLine($"[{sw.Elapsed.TotalSeconds:0.0}s] await t4 gave: {Name(typeof(Task<int>))} (not int)");
// Fix 1: await twice
int v1 = await await Task.Factory.StartNew(async () => { await X(); return 42; });
Console.WriteLine($"[{sw.Elapsed.TotalSeconds:0.0}s] await await t4 = {v1}");
// Fix 2: Unwrap()
int v2 = await Task.Factory.StartNew(async () => { await X(); return 42; }).Unwrap();
Console.WriteLine($"[{sw.Elapsed.TotalSeconds:0.0}s] t4.Unwrap() = {v2}");
// Best: Task.Run unwraps automatically
int v3 = await Task.Run(async () => { await X(); return 42; });
Console.WriteLine($"[{sw.Elapsed.TotalSeconds:0.0}s] await t8 = {v3} (Task.Run unwraps for you)");
}
}