Created
August 3, 2022 08:36
-
-
Save neuecc/33b0a74957e63587b61541d1ac9da08f to your computer and use it in GitHub Desktop.
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
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