Created
August 3, 2022 07:45
-
-
Save neuecc/0471eaac3ede0bdc2a4e85cbef7c0745 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) | |
{ | |
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | |
cts.CancelAfter(Timeout); | |
try | |
{ | |
await SendCoreAsync(cts.Token); | |
} | |
catch (OperationCanceledException ex) when (ex.CancellationToken == cts.Token) | |
{ | |
if (cancellationToken.IsCancellationRequested) | |
{ | |
// Error reason is argument CancellationToken, hold token in new OperationCanceledException | |
throw new OperationCanceledException(ex.Message, ex, cancellationToken); | |
} | |
else | |
{ | |
// Error reason is timeout, throw TimeoutException(or any custom exception) | |
throw new TimeoutException($"The request was canceled due to the configured Timeout of {Timeout.TotalSeconds} seconds elapsing.", ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment