47
loading...
This website collects cookies to deliver better user experience
async/await
pattern in C# 5.0 back in 2011. I think it’s one of the greatest contributions to the asynchronous programming — at languages level— which led other programming languages to follow, like Python and JavaScript, to name a few. It makes asynchronous code more readable, more like the ordinary synchronous code. Remember those old-school BeginXxx
/ EndXxx
in Asynchronous Programming Model/APM in C# 1.0? I can still remember writing those in 2002 with Visual Studio .NET 2002.await ReadAsync()
?😆await MethodAsync()
in the kitchen and then leaves the kitchen without waiting for the 🍜(Task<🍜>) to be ready. Our synchronous chef, whereas, in contrast, will be hanging around, perhaps forever in the kitchen, waiting for the 🍜.ConfigureAwait(false)
; trying to simulate “no Synchronization Context” here). At this point, we are in the so-called “there is no thread” state. Nobody is in the kitchen. Our 🍜 is still sitting in the microwave (ongoing I/O operation). Sorry to disappoint you, my dear reader, it’s instant noodles 😂.AsyncStateMachine
). The rest is the same as the synchronous version.var builder = WebApplication.CreateBuilder(args);
await using var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapGet("/sleep", (CancellationToken cancellationToken) =>
{
while (!cancellationToken.IsCancellationRequested)
{
Enumerable.Range(1, 100).Select(x => x).ToList().ForEach(x =>
{
//WARNING: BAD CODE
Task.Run(() => Thread.Sleep(3 * 60 * 1_000), cancellationToken);
});
Thread.Sleep(2 * 60 * 1_000);
}
return "Done.";
});
app.MapGet("/delay", async (CancellationToken cancellationToken) =>
{
while (!cancellationToken.IsCancellationRequested)
{
Enumerable.Range(1, 100).Select(x => x).ToList().ForEach(x =>
{
//WARNING: BAD CODE
Task.Run(async () => await Task.Delay(3 * 60 * 1_000, cancellationToken), cancellationToken);
});
await Task.Delay(2 * 60 * 1_000, cancellationToken);
}
return "Done.";
});
await app.RunAsync();
📝 Even though we are calling Thread.Sleep
, it’s still a waste of resources.
📝 You can use Debugger.Break
to achieve the same effect. Details: https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.break