4 ms·
A good way across languages to cancel an asynchronous task is by passing a CancellationToken / AbortSignal (Javascript) as an argument. This scales nicely as a
by AgentME 4y ago
A good way across languages to cancel an asynchronous task is by passing a CancellationToken / AbortSignal (Javascript) as an argument. This scales nicely as a task can pass the token onward to any number of other tasks, and the original creator of the token can abort it and all uses of it at any time.
- e12e 4y agoFeels like this should be a language feature, though - like how python passes self for objects - or ruby binds self for you?
- AgentME 4y agoKotlin has "structured concurrency" which I believe automatically handles some cases of this, but I don't fully understand it. I find explicit cancellation tokens without any magic easier to understand.
- sbf501 4y agoI remember a github repo like this from ages ago. How is the token used? I assume the token has a function that triggers an abort, but does that mean the downstream code has to constantly check the token, or does it simply generate a fault/exception at the lowest level that bubbles upstream? I'm not sure of the token mechanics.
- AgentME 4y agoIt works like your first guess, but it's not so bad. Downstream code has to either check the token occasionally, subscribe to an event from it, or just pass it forward to another function which uses the token. So if you were writing a function that just made a series of network requests, you would make it take a CancellationToken as a parameter, and then you would pass that parameter on to each of the network request function calls inside your function. Then if the token is in the aborted state while any of the network function calls are in-progress, then that network function call will throw an exception which will bubble up through your function, without your function needing to do anything special with the CancellationToken directly.
- zaphar 4y agoThis is the primary use-case for Contexts in go. It's standard practice to pass contexts through all your concurrent code and abort on the `Cancel` call.