📖 Scenario: Imagine you are building a simple program that fetches data from the internet and then shows it to the user. Normally, the program waits and does nothing else until the data arrives. This waiting can make the program feel slow or frozen.
🎯 Goal: You will create a small program that simulates waiting for data, then learn how to use async programming to avoid freezing the program while waiting.
📋 What You'll Learn
Create a method that simulates a delay to represent waiting for data
Create a variable to hold the waiting time in milliseconds
Use async and await keywords to run the waiting without blocking the program
Print messages before and after waiting to show the program flow
💡 Why This Matters
🌍 Real World
Async programming is used in apps that fetch data from the internet, read files, or do long tasks without freezing the screen.
💼 Career
Understanding async helps you build smooth, fast apps that users enjoy, a key skill for software developers.
Progress0 / 4 steps
1
Create a method to simulate waiting
Create a method called WaitForData that takes no parameters and uses Thread.Sleep(3000) to simulate waiting for 3 seconds.
C Sharp (C#)
Hint
Use Thread.Sleep(3000) inside the method to pause for 3 seconds.
2
Add a variable for waiting time
Inside the Main method, create an integer variable called waitTime and set it to 3000.
C Sharp (C#)
Hint
Declare int waitTime = 3000; inside Main.
3
Make the waiting method async
Change the WaitForData method to be async and return a Task. Inside it, replace Thread.Sleep(3000) with await Task.Delay(waitTime). Also, add using System.Threading.Tasks; at the top. Pass waitTime as a parameter to WaitForData.
C Sharp (C#)
Hint
Use async Task for the method and await Task.Delay(waitTime); inside.
4
Call the async method and print messages
In the Main method, print "Start waiting...", then call WaitForData(waitTime).GetAwaiter().GetResult() to wait for completion, then print "Done waiting!".
C Sharp (C#)
Hint
Use Console.WriteLine to print messages and call the async method with .GetAwaiter().GetResult() to wait synchronously.
Practice
(1/5)
1. Why do we need async programming in C# applications?
easy
A. To reduce the size of the compiled program
B. To make the code run faster by using more CPU cores
C. To avoid writing any loops in the code
D. To keep the app responsive during long-running tasks
Solution
Step 1: Understand app responsiveness
When an app does a slow task like reading a file, it can freeze if it waits synchronously.
Step 2: Role of async programming
Async lets the app pause the slow task and do other things, keeping the interface responsive.
Final Answer:
To keep the app responsive during long-running tasks -> Option D
Quick Check:
Async = Responsiveness [OK]
Hint: Async keeps UI smooth during slow tasks [OK]
Common Mistakes:
Thinking async makes code run faster on CPU
Confusing async with parallel processing
Believing async reduces program size
2. Which of the following is the correct way to declare an async method in C#?
easy
A. public void async LoadData()
B. public async void LoadData()
C. async public LoadData() void
D. public LoadData async void()
Solution
Step 1: Recall async method syntax
In C#, async keyword comes before the return type, e.g., public async Task or public async void.
Step 2: Check each option
Only public async void LoadData() correctly places async before the return type void.
Final Answer:
public async void LoadData() -> Option B
Quick Check:
async before return type = public async void LoadData() [OK]
Hint: async keyword goes before return type [OK]
Common Mistakes:
Placing async after return type
Putting async after method name
Incorrect order of keywords
3. What will be the output of this C# code snippet?
async Task<string> GetDataAsync() {
await Task.Delay(1000);
return "Done";
}
var task = GetDataAsync();
Console.WriteLine("Waiting...");
var result = task.Result;
Console.WriteLine(result);
medium
A. Waiting...\nDone
B. Done\nWaiting...
C. Waiting... only
D. Runtime error due to deadlock
Solution
Step 1: Understand async method behavior
The method returns a Task that completes after 1 second delay, then returns "Done".
Step 2: Analyze code execution order
"Waiting..." prints immediately, then task.Result blocks until the async method finishes, then prints "Done".
Final Answer:
Waiting...\nDone -> Option A
Quick Check:
Print order = Waiting... then Done [OK]
Hint: Console.WriteLine before await completes prints first [OK]
Common Mistakes:
Assuming async method runs instantly
Confusing order of prints
Expecting deadlock without synchronization context
4. Identify the problem in this async method and how to fix it:
public async void FetchData() {
var data = GetData();
Console.WriteLine(data);
}
string GetData() {
Thread.Sleep(2000);
return "Data loaded";
}
medium
A. Console.WriteLine should be awaited
B. FetchData should not be async void, change to async Task
C. GetData blocks thread; use async GetDataAsync with await
D. Thread.Sleep should be replaced with Task.Run
Solution
Step 1: Identify blocking call
GetData uses Thread.Sleep which blocks the thread, causing UI freeze despite async method.
Step 2: Fix by making GetData async
Replace GetData with an async version using Task.Delay and await it in FetchData to avoid blocking.
Final Answer:
GetData blocks thread; use async GetDataAsync with await -> Option C
Quick Check:
Blocking call in sync method = GetData blocks thread; use async GetDataAsync with await [OK]
Hint: Avoid Thread.Sleep in async methods; use await Task.Delay [OK]
Common Mistakes:
Only changing FetchData signature without fixing blocking call
Trying to await Console.WriteLine
Replacing Thread.Sleep with Task.Run without await
5. You want to download multiple files without freezing your app. Which approach best uses async programming to achieve this?
hard
A. Start all downloads with async methods and await them all with Task.WhenAll
B. Download files one by one synchronously to avoid complexity
C. Use Thread.Sleep between downloads to simulate delay
D. Run downloads on separate threads without async/await
Solution
Step 1: Understand async for multiple tasks
Starting downloads asynchronously lets them run concurrently without blocking UI.
Step 2: Use Task.WhenAll to await all
Task.WhenAll waits for all downloads to finish efficiently, keeping app responsive.
Final Answer:
Start all downloads with async methods and await them all with Task.WhenAll -> Option A