Created
September 6, 2023 06:12
-
-
Save admir-live/3a90095412dc91f26bd867dba155ad42 to your computer and use it in GitHub Desktop.
AsyncExamples.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net.Http; | |
using System.Threading.Tasks; | |
public class AsyncExamples | |
{ | |
// GOOD EXAMPLE | |
// This method performs an asynchronous operation and hence uses async and await appropriately. | |
public async Task<string> GetDataAsync() | |
{ | |
HttpClient client = new HttpClient(); | |
// The following line makes an asynchronous call to get data from the web. | |
// Using await here ensures that the method yields control and doesn't block the caller while waiting. | |
string data = await client.GetStringAsync("https://example.com/data"); | |
return data; | |
} | |
// BAD EXAMPLE | |
// This method does not have any asynchronous operations, yet it's marked as async. | |
// This introduces unnecessary overhead due to the compiler-generated state machine. | |
public async Task<string> GetStaticMessageAsync() | |
{ | |
// The method simply returns a static string without any asynchronous operations. | |
// The async keyword is redundant here. | |
return "Hello, World!"; | |
} | |
} | |
// In summary: | |
// 1. When a method genuinely benefits from being asynchronous, use the async and await keywords together. | |
// 2. If a method doesn't have any asynchronous operations, avoid marking it as async. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment