Skip to content

Instantly share code, notes, and snippets.

@neuecc
Created August 3, 2022 07:45
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/0471eaac3ede0bdc2a4e85cbef7c0745 to your computer and use it in GitHub Desktop.
Save neuecc/0471eaac3ede0bdc2a4e85cbef7c0745 to your computer and use it in GitHub Desktop.
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