Why async programming is needed in C Sharp (C#) - Performance Analysis
When programs wait for slow tasks like reading files or web data, they can freeze and waste time.
We want to see how using async programming changes how long the program takes as tasks grow.
Analyze the time complexity of the following code snippet.
public async Task DownloadFilesAsync(List<string> urls)
{
foreach (var url in urls)
{
var data = await DownloadFileAsync(url);
ProcessData(data);
}
}
// Simulates downloading a file asynchronously
public async Task<byte[]> DownloadFileAsync(string url)
{
await Task.Delay(1000); // Simulate network delay
return new byte[100];
}
This code downloads files one by one, waiting for each to finish before starting the next.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that downloads each file one after another.
- How many times: Once for each file in the list.
Each file download waits about 1 second before moving on to the next.
| Input Size (n) | Approx. Operations (seconds) |
|---|---|
| 10 | ~10 seconds (10 downloads x 1 second each) |
| 100 | ~100 seconds |
| 1000 | ~1000 seconds |
Pattern observation: The total time grows directly with the number of files because each waits for the previous to finish.
Time Complexity: O(n)
This means the total time grows in a straight line as you add more files to download one after another.
[X] Wrong: "Using async means all downloads happen at the same time, so time stays the same no matter how many files."
[OK] Correct: In this code, downloads happen one after another because of the await inside the loop, so time still adds up with each file.
Understanding how async code runs step-by-step helps you explain how programs stay responsive and handle many tasks without waiting too long.
"What if we started all downloads at once and then waited for all to finish? How would the time complexity change?"