Bird
Raised Fist0
C Sharp (C#)programming~20 mins

Task.WhenAny for first completion in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Task.WhenAny Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Task.WhenAny with different delays
What will be the output of this C# code snippet using Task.WhenAny to await the first completed task?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var task1 = Task.Delay(300).ContinueWith(_ => "Task1");
        var task2 = Task.Delay(100).ContinueWith(_ => "Task2");
        var task3 = Task.Delay(200).ContinueWith(_ => "Task3");

        var firstCompleted = await Task.WhenAny(task1, task2, task3);
        Console.WriteLine(await firstCompleted);
    }
}
ATask1
BTask2
CTask3
DCompilation error
Attempts:
2 left
💡 Hint
Think about which task finishes first based on the delay times.
🧠 Conceptual
intermediate
1:30remaining
Understanding Task.WhenAny behavior
Which statement best describes what Task.WhenAny does in C#?
AIt cancels all other tasks once the first task completes.
BIt waits for all tasks to complete and returns their results as a list.
CIt returns the first task that completes, regardless of success or failure.
DIt throws an exception if any task fails before completion.
Attempts:
2 left
💡 Hint
Consider what happens if one task completes with an error before others finish.
🔧 Debug
advanced
2:00remaining
Identify the runtime error with Task.WhenAny usage
What runtime error will this code produce when executed?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Task<string> task1 = Task.FromResult("Hello");
        Task<string> task2 = null;

        var first = await Task.WhenAny(task1, task2);
        Console.WriteLine(await first);
    }
}
AArgumentNullException
BNullReferenceException
CInvalidOperationException
DNo error, outputs "Hello"
Attempts:
2 left
💡 Hint
Check what happens if one of the tasks passed to Task.WhenAny is null.
❓ Predict Output
advanced
2:00remaining
Output when first completed task faults
What will be the output of this code snippet?
C Sharp (C#)
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var task1 = Task.Run(() => throw new InvalidOperationException("Error in task1"));
        var task2 = Task.Delay(100).ContinueWith(_ => "Success");

        var first = await Task.WhenAny(task1, task2);

        try
        {
            Console.WriteLine(await first);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.GetType().Name);
        }
    }
}
ASuccess
BCompilation error
CTaskCanceledException
DInvalidOperationException
Attempts:
2 left
💡 Hint
Consider which task completes first and what happens when awaiting a faulted task.
🚀 Application
expert
3:00remaining
Using Task.WhenAny to implement a timeout
Which code snippet correctly uses Task.WhenAny to implement a 500ms timeout for an asynchronous operation DoWorkAsync()? The code should print "Timeout" if the operation takes too long, or print the result if it completes in time.
A
var workTask = DoWorkAsync();
var timeoutTask = Task.Delay(500);
var first = await Task.WhenAny(workTask, timeoutTask);
if (first == timeoutTask) Console.WriteLine("Timeout");
else Console.WriteLine(await workTask);
B
var workTask = DoWorkAsync();
var timeoutTask = Task.Delay(500);
var first = await Task.WhenAny(workTask, timeoutTask);
if (first == workTask) Console.WriteLine("Timeout");
else Console.WriteLine(await timeoutTask);
C
var workTask = DoWorkAsync();
var timeoutTask = Task.Delay(500);
await Task.WhenAny(workTask, timeoutTask);
if (workTask.IsCompleted) Console.WriteLine("Timeout");
else Console.WriteLine(await workTask);
D
var workTask = DoWorkAsync();
var timeoutTask = Task.Delay(500);
var first = await Task.WhenAny(workTask, timeoutTask);
if (first == timeoutTask) Console.WriteLine(await timeoutTask);
else Console.WriteLine("Timeout");
Attempts:
2 left
💡 Hint
Check which task finished first and print accordingly.

Practice

(1/5)
1. What does Task.WhenAny do in C#?
easy
A. It creates a new task that never completes.
B. It waits for all tasks to complete before continuing.
C. It cancels all running tasks immediately.
D. It waits for the first task to complete among multiple tasks.

Solution

  1. Step 1: Understand Task.WhenAny purpose

    Task.WhenAny waits for the first task to finish among many tasks.
  2. Step 2: Compare with other options

    Unlike Task.WhenAll, it does not wait for all tasks, nor does it cancel tasks or create infinite tasks.
  3. Final Answer:

    It waits for the first task to complete among multiple tasks. -> Option D
  4. Quick Check:

    Task.WhenAny = first task completion [OK]
Hint: Remember: WhenAny means wait for one task only [OK]
Common Mistakes:
  • Confusing Task.WhenAny with Task.WhenAll
  • Thinking it cancels other tasks
  • Assuming it waits for all tasks
2. Which of the following is the correct syntax to use Task.WhenAny with two tasks task1 and task2?
easy
A. var first = await Task.WhenAny(task1, task2);
B. var first = await Task.WhenAny([task1, task2]);
C. var first = await Task.WhenAny{task1, task2};
D. var first = await Task.WhenAny task1, task2;

Solution

  1. Step 1: Check correct method call syntax

    Task.WhenAny accepts params array of tasks, so calling with (task1, task2) is correct.
  2. Step 2: Identify invalid syntax

    Square brackets, curly braces, or missing parentheses cause syntax errors.
  3. Final Answer:

    var first = await Task.WhenAny(task1, task2); -> Option A
  4. Quick Check:

    Correct method call uses parentheses and comma-separated tasks [OK]
Hint: Use parentheses and commas for Task.WhenAny arguments [OK]
Common Mistakes:
  • Using square brackets instead of parentheses
  • Using curly braces instead of parentheses
  • Omitting parentheses around arguments
3. What will be the output of this code snippet?
var task1 = Task.Delay(3000).ContinueWith(_ => "Task1 done");
var task2 = Task.Delay(1000).ContinueWith(_ => "Task2 done");
var first = await Task.WhenAny(task1, task2);
Console.WriteLine(await first);
medium
A. Task2 done
B. No output, program hangs
C. Task1 done\nTask2 done
D. Task1 done

Solution

  1. Step 1: Analyze task delays

    task1 completes after 3000ms, task2 after 1000ms, so task2 finishes first.
  2. Step 2: Task.WhenAny returns first completed task

    first will be task2, so awaiting it prints "Task2 done".
  3. Final Answer:

    Task2 done -> Option A
  4. Quick Check:

    First completed task result = Task2 done [OK]
Hint: The shortest delay task finishes first [OK]
Common Mistakes:
  • Assuming task1 finishes first because it is listed first
  • Expecting both tasks to print
  • Thinking program hangs waiting for all tasks
4. Identify the error in this code using Task.WhenAny:
var task1 = Task.Delay(2000);
var task2 = Task.Delay(1000);
var first = Task.WhenAny(task1, task2);
Console.WriteLine(await first.Result);
medium
A. Using await on first.Result causes a compile error.
B. Task.WhenAny should be awaited before accessing Result.
C. Task.Delay cannot be used with Task.WhenAny.
D. Console.WriteLine cannot print task results.

Solution

  1. Step 1: Check how Task.WhenAny is awaited

    Task.WhenAny returns a Task<Task>, so it must be awaited to get the completed task.
  2. Step 2: Identify misuse of Result property

    Accessing first.Result without awaiting first causes incorrect behavior or deadlock.
  3. Final Answer:

    Task.WhenAny should be awaited before accessing Result. -> Option B
  4. Quick Check:

    Await Task.WhenAny before accessing completed task [OK]
Hint: Always await Task.WhenAny before using its result [OK]
Common Mistakes:
  • Accessing Result property without await
  • Confusing Task<Task> with Task
  • Ignoring async/await pattern
5. You have three tasks: taskA (2s delay), taskB (1s delay), and taskC (3s delay). You want to print the result of the first completed task and then cancel the other two tasks. Which code snippet correctly achieves this?
hard
A. var first = await Task.WhenAny(taskA, taskB, taskC); cts.Cancel(); Console.WriteLine(await first);
B. var first = await Task.WhenAny(taskA, taskB, taskC); Console.WriteLine(await first); // No cancellation code
C. var cts = new CancellationTokenSource(); var taskA = Task.Delay(2000, cts.Token); var taskB = Task.Delay(1000, cts.Token); var taskC = Task.Delay(3000, cts.Token); var first = await Task.WhenAny(taskA, taskB, taskC); cts.Cancel(); Console.WriteLine(await first);
D. var first = Task.WhenAny(taskA, taskB, taskC).Result; cts.Cancel(); Console.WriteLine(first.Result);

Solution

  1. Step 1: Use CancellationTokenSource to cancel tasks

    Create a CancellationTokenSource and pass its token to all tasks so they can be cancelled.
  2. Step 2: Await Task.WhenAny and cancel remaining tasks

    Await Task.WhenAny to get first completed task, then call cts.Cancel() to stop others, finally print the result.
  3. Final Answer:

    Use CancellationTokenSource, await Task.WhenAny, then cancel and print. -> Option C
  4. Quick Check:

    Cancel tasks after first completion using CancellationTokenSource [OK]
Hint: Pass cancellation token to tasks and cancel after first finishes [OK]
Common Mistakes:
  • Not passing cancellation token to tasks
  • Calling Cancel before awaiting Task.WhenAny
  • Using .Result instead of await causing deadlocks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard