I have a question about what mechanism to cancel an ongoing async operation could be used, instead a cancellation token in the async/await context. I'm sure this is a well studied design decision that takes into account the imperative nature of the language, but in real situations having to pass a cancellation object to all your async methods is, at least, a bit painful. There are another design ideas from the c# community, or the proposed cancellation mechanism is just OK? I think I'm missing something.
The cancellation token is the best practice, especially when the asynchronous process is expensive, has no preset ending condition, or involves external resources.
However, you can, if you wish, simply "give up". Instead of telling the async thread to abort processing and clean up, just "time out"; stop waiting for it to complete, detach any listeners, and keep running. When the thread eventually does complete, it'll check its event, realize nobody's listening, and silently terminate. The upside is the simplicity, however there are many situations in which this would be a BAD thing:
In order for cancellation of an async operation to make sense, that operation must perform discreet steps, since it is up the operation to check the cancellation token and stop itself from continuing. I.e. the cancellation token is merely a pattern to be implemented not a mechanism of async/await.
What that means it that if your async operation is just one I/O call with a completion handle, you might as well, just give up rather than cancel, since the operation will not have the oppurtunity to check your token until that call comes back at which point there is nothing to be gained.
So when considering a cancellation token, first consider whether this operation can be made more efficient by supporting cancellation or whether just not waiting for it to complete (i.e. using a timeout mechanism instead) makes more sense.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With