0
0
C Sharp (C#)programming~30 mins

Why async programming is needed in C Sharp (C#) - See It in Action

Choose your learning style9 modes available
Why async programming is needed
📖 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#)
Need a 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#)
Need a 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#)
Need a 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#)
Need a hint?

Use Console.WriteLine to print messages and call the async method with .GetAwaiter().GetResult() to wait synchronously.