Created
March 28, 2024 05:00
-
-
Save normanlmfung/f6fbb0ab7742e658f43867ca4ca55150 to your computer and use it in GitHub Desktop.
csharp_async
This file contains hidden or 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; | |
class Program { | |
static async Task Main(string[] args) | |
{ | |
// Example 1. await-foreach | |
static async IAsyncEnumerable<int> YieldReturnNumbers(List<int> numbers) | |
{ | |
foreach (int number in numbers) | |
{ | |
await Task.Delay(1000); | |
yield return number; | |
} | |
} | |
static async Task TestAwaitForEach() { | |
List<int> numbers = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; | |
await foreach(int number in YieldReturnNumbers(numbers)) | |
{ | |
Console.WriteLine(number); | |
} | |
} | |
await TestAwaitForEach(); | |
// Example 2. Simple async method call and ConfigureAwait | |
static async Task SimpleFetch() | |
{ | |
using(var client = new HttpClient()) { | |
Console.WriteLine($"Simple Async #2. Thread ID: {Thread.CurrentThread.ManagedThreadId}"); | |
var response = await client.GetAsync(new Uri("http://bbc.co.uk")).ConfigureAwait(true); | |
Console.WriteLine($"Simple Async #3. Thread ID: {Thread.CurrentThread.ManagedThreadId}"); | |
} | |
} | |
Console.WriteLine($"Simple Async #1. Thread ID: {Thread.CurrentThread.ManagedThreadId}"); | |
await SimpleFetch().ConfigureAwait(true); | |
await Task.Delay(100).ConfigureAwait(true); | |
/* | |
Why after 'await', even with ConfigureAwait(true), thread id not returning to main thread? | |
Essentially for dotnet core console and aspnet core/webapi's, ConfigureAwait essentially making random decision which thread to execute continuation tasks, because no synchronization context present. | |
https://stackoverflow.com/questions/78229368/dotnet-core-console-app-configureawaittrue | |
https://stackoverflow.com/questions/13489065/best-practice-to-call-configureawait-for-all-server-side-code | |
*/ | |
Console.WriteLine($"Simple Async #4. Thread ID: {Thread.CurrentThread.ManagedThreadId}"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment