Select in C#
C# doesn’t have a direct equivalent to Go’s select
statement for channel operations. However, we can achieve similar functionality using Task
s and async/await
. Here’s how we can translate the concept:
In this C# version:
We use
Task
s instead of channels to represent asynchronous operations.Each task simulates a blocking operation by using
Task.Delay()
.We use
Task.WhenAny()
to wait for either task to complete, which is similar to theselect
statement in the original example.We use a
for
loop to process both tasks, similar to the original example.After a task completes, we replace it with a never-completing task (
Task.Delay(-1)
) to ensure it’s not selected again in the next iteration.
To run the program, save it as Select.cs
and use the dotnet
CLI:
Note that the total execution time is only ~2 seconds since both the 1 and 2 second delays execute concurrently.
This example demonstrates how to work with multiple asynchronous operations in C#, waiting for them to complete in any order. While it’s not identical to Go’s select
, it achieves a similar purpose of handling concurrent operations efficiently.