Task and Task of T types in C Sharp (C#) - Time & Space Complexity
When working with asynchronous code using Task and Task<T>, it's important to understand how the time to complete tasks grows as you start more tasks or wait for their results.
We want to see how the time needed changes when handling multiple tasks.
Analyze the time complexity of the following code snippet.
public async Task<int> SumAsync(int[] numbers)
{
var tasks = new List<Task<int>>();
foreach (var num in numbers)
{
tasks.Add(Task.Run(() => num));
}
var results = await Task.WhenAll(tasks);
return results.Sum();
}
This code creates a task for each number to return it asynchronously, waits for all tasks to finish, then sums the results.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and running one task per number in the input array.
- How many times: Once for each element in the input array (n times).
As the input array grows, the number of tasks created and awaited grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 tasks created and awaited |
| 100 | About 100 tasks created and awaited |
| 1000 | About 1000 tasks created and awaited |
Pattern observation: The work grows directly with the number of input items, so doubling input doubles the work.
Time Complexity: O(n)
This means the time to complete grows linearly with the number of tasks you start and wait for.
[X] Wrong: "Starting many tasks at once makes the program run instantly regardless of input size."
[OK] Correct: Even though tasks run asynchronously, creating and waiting for many tasks still takes time proportional to how many tasks there are.
Understanding how asynchronous tasks scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we changed Task.WhenAll to await each task one by one? How would the time complexity change?"
Practice
Task and Task<T> in C#?Solution
Step 1: Understand
TaskbehaviorTaskrepresents an asynchronous operation that does not return a result.Step 2: Understand
Task<T>behaviorTask<T>represents an asynchronous operation that returns a value of typeTwhen it completes.Final Answer:
Taskdoes not return a value,Task<T>returns a value of typeT. -> Option AQuick Check:
Return value presence =Taskdoes not return a value,Task<T>returns a value of typeT. [OK]
- Thinking Task runs synchronously
- Confusing Task<T> with multiple return values
- Assuming Task is only for UI threads
Task<int> that returns the number 5 asynchronously?Solution
Step 1: Check correct Task<T> creation syntax
UseTask.Run(() => value)to create and start a task returning a value.Step 2: Validate each option
Task<int> t = Task.Run(() => 5); usesTask.Run(() => 5), which is correct. Options A, B, and C use invalid constructors or methods.Final Answer:
Task<int> t = Task.Run(() => 5); -> Option AQuick Check:
Correct Task creation syntax = Task<int> t = Task.Run(() => 5); [OK]
- Trying to pass value directly to Task constructor
- Using non-existent Task.Run overloads
- Confusing Task and Task<T> creation
async Task<int> GetNumberAsync() { return 10; }
var task = GetNumberAsync();
Console.WriteLine(task.Result);Solution
Step 1: Understand async method returning Task<int>
The method returns a Task that completes with value 10.Step 2: Accessing
Accessingtask.ResultResultblocks until the task finishes and returns 10.Final Answer:
10 -> Option BQuick Check:
Task.Result blocks and returns value = 10 [OK]
- Expecting Task<int> printed instead of value
- Thinking async method returns int directly
- Assuming runtime error without synchronization context
Task<int> task = Task.Run(() => 42); int result = await task;
Solution
Step 1: Check usage of await keyword
awaitcan only be used inside methods marked withasync.Step 2: Analyze code context
The snippet does not show an async method, so usingawaithere causes a compile error.Final Answer:
Cannot use await outside an async method -> Option CQuick Check:
Await requires async method = Cannot use await outside an async method [OK]
- Assuming Task.Run cannot return int
- Thinking Task<int> can be void
- Ignoring async keyword requirement for await
Solution
Step 1: Understand parallel task waiting
Task.WhenAllwaits for all tasks to complete concurrently.Step 2: Access results after waiting
Afterawait Task.WhenAll(...), you can safely access each task'sResultwithout blocking.Final Answer:
Useawait Task.WhenAll(task1, task2)then accesstask1.Resultandtask2.Result. -> Option DQuick Check:
Parallel wait with Task.WhenAll = Useawait Task.WhenAll(task1, task2)then accesstask1.Resultandtask2.Result. [OK]
- Waiting tasks sequentially losing parallelism
- Using blocking Wait() causing deadlocks
- Casting results instead of accessing Task<T>.Result
Ready to prove it?
Pass the test and this pattern moves unknown
