3 ms·
Fan-in, as described in the proposal: void serve(ServerSocket serverSocket) throws IOException, InterruptedException { try (var scope = new Structu
by neonsunset 2y ago
Fan-in, as described in the proposal:
void serve(ServerSocket serverSocket) throws IOException, InterruptedException {
try (var scope = new StructuredTaskScope<Void>()) {
try {
while (true) {
var socket = serverSocket.accept();
scope.fork(() -> handle(socket));
}
} finally {
// If there's been an error or we're interrupted, we stop accepting
scope.shutdown(); // Close all active connections
scope.join();
}
}
}
It's not exactly clear the exact specifics of how the above works regarding child tasks being able or unable to shutdown the parent scope - it only has the exception handler for the loop itself, which then performs .shutdown, which interrupts all the child tasks.
However, if we continue with this assumption, then C# implementation is just the following:
async Task Serve(Socket socket) {
using var cts = new CancellationTokenSource();
try {
while (true) {
var conn = await socket.AcceptAsync(cts.Token);
// Or pass cts to Handle itself if you want to allow the handler to cancel the listener task.
_ = Task.Run(() => Handle(conn, cts.Token));
}
}
finally { cts.Cancel(); }
}
With that said, the difference to Java Structured Concurrency as proposed is that it offers tree-like tracking of child tasks/green threads, control over their execution, and, possibly, nicer debugging experience.
I don't have an opinion whether the semantics of .shutdown() which ends up calling .interrupt() are sound without reading more carefully. If it can interrupt the execution at any point, this is extremely dangerous and will break a lot of existing code. It's one of the reasons why thread.Abort() got deprecated in .NET - the API brings too many issues and cannot be made to work reliably without hindering optimizations or violating expectations.
If it's not the case and it's more like flowing CancellationToken implicitly, then it may be a nicer experience depending on the situation. If it only interrupts upon suspending on .Join, IO wait or similar - it's still the kind of API that you are forced into instead of deciding whether cooperative cancellation is even safely possible given specific logic, without having to write try-catch blocks for each callsite. This is my surface impression and I will continue looking into this API.