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

Async and await keywords in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Async and await keywords
📖 Scenario: You are building a simple console app that fetches data from a server. To keep the app responsive, you will use async and await keywords to handle the data fetching without blocking the main thread.
🎯 Goal: Create an asynchronous method to simulate fetching data, then call it using await and display the result.
📋 What You'll Learn
Create an asynchronous method called FetchDataAsync that returns a Task<string>.
Inside FetchDataAsync, simulate a delay of 2 seconds using Task.Delay.
Return a string message from FetchDataAsync after the delay.
In the Main method, call FetchDataAsync using await and store the result in a variable called data.
Print the data variable to the console.
💡 Why This Matters
🌍 Real World
Many apps need to fetch data from the internet or perform long tasks without freezing the screen. Using <code>async</code> and <code>await</code> helps keep apps smooth and responsive.
💼 Career
Understanding asynchronous programming is essential for software developers working on web apps, desktop apps, or any program that handles input/output or network calls efficiently.
Progress0 / 4 steps
1
Create the asynchronous method
Create an asynchronous method called FetchDataAsync that returns Task<string>. Inside it, simulate a 2-second delay using await Task.Delay(2000). After the delay, return the string "Data fetched successfully".
C Sharp (C#)
Need a hint?

Use async before the method return type and await Task.Delay(2000) to simulate waiting.

2
Call the asynchronous method with await
Inside the Main method, call FetchDataAsync using await and store the result in a variable called data.
C Sharp (C#)
Need a hint?

Use string data = await FetchDataAsync(); inside Main.

3
Print the fetched data
Add a Console.WriteLine statement inside the Main method to print the data variable.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(data); to show the result.

4
Run and see the output
Run the program and observe the output. It should print Data fetched successfully after a 2-second delay.
C Sharp (C#)
Need a hint?

Wait 2 seconds, then see the message printed.