Skip to content

Instantly share code, notes, and snippets.

@adamralph
Last active May 26, 2021 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamralph/b4c3eb91472d1e2d66e34a76e2a10e5c to your computer and use it in GitHub Desktop.
Save adamralph/b4c3eb91472d1e2d66e34a76e2a10e5c to your computer and use it in GitHub Desktop.
a fanciful idea about a better form of cancellation in C#
// 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