Last active
May 26, 2021 13:16
-
-
Save adamralph/b4c3eb91472d1e2d66e34a76e2a10e5c to your computer and use it in GitHub Desktop.
a fanciful idea about a better form of cancellation in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// a fanciful idea about a better form of cancellation in C# | |
try | |
{ | |
Foo(cancellationToken); | |
} | |
catch (Cancellation cancellation) // System.Cancellation - does NOT inherit from System.Exception, but still has a stack trace, etc. | |
{ | |
} | |
catch (Exception ex) | |
{ | |
} | |
finally | |
{ | |
} | |
// cancel is a new keyword and param modifier | |
// more than one cancel param can be declared, although that's probably quite unusual | |
// the param is implicitly an optional CancellationToken | |
// the default value is CancellationToken.None | |
// the return type of Foo would probably be Task-like in most cases, but that's irrelevant | |
void Foo(cancel cancellationToken) | |
{ | |
// can still check if the token is cancelled, etc. | |
if (cancellationToken.IsCancellationRequested) | |
{ | |
} | |
// can still create linked token sources, etc. | |
var src = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, myToken); | |
// can only throw a Cancellation with yield cancel, a new keyword combination | |
// yield cancel only throws a Cancellation if at least one cancel arg has IsCancellationRequested == true | |
yield cancel; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment