Skip to content

Instantly share code, notes, and snippets.

@neuecc
Created August 3, 2022 08:36
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 neuecc/33b0a74957e63587b61541d1ac9da08f to your computer and use it in GitHub Desktop.
Save neuecc/33b0a74957e63587b61541d1ac9da08f to your computer and use it in GitHub Desktop.
public async Task SendAsync(CancellationToken cancellationToken = default)
{
var timeoutTokenSource = timeoutTokenSourcePool.Get();
CancellationTokenRegistration externalCancellation = default;
if (cancellationToken.CanBeCanceled)
{
// When raised argument CancellationToken, raise Timeout's CancellationToken
externalCancellation = cancellationToken.UnsafeRegister(static state =>
{
((CancellationTokenSource)state!).Cancel();
}, timeoutTokenSource);
}
timeoutTokenSource.CancelAfter(Timeout);
try
{
await SendCoreAsync(timeoutTokenSource.Token);
}
finally
{
// Unregister(must before `TryReset`),
// CancellationTokenRegistration.Dispose block and wait reliably until the release is completed (or the execution is finished if a callback is being executed)
externalCancellation.Dispose();
if (timeoutTokenSource.TryReset())
{
timeoutTokenSourcePool.Return(timeoutTokenSource);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment