Skip to content

Instantly share code, notes, and snippets.

@neuecc
Last active August 3, 2022 08:32
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/134a1d3588f27965e4e6b604bd19d571 to your computer and use it in GitHub Desktop.
Save neuecc/134a1d3588f27965e4e6b604bd19d571 to your computer and use it in GitHub Desktop.
class Client
{
// For classes that prohibit multiple calls to methods such as SqlConnection, add a single CancellationTokenSource to the field
// Things like HttpClient, which may be called multiple times, are held in ObjectPool.
readonly ObjectPool<CancellationTokenSource> timeoutTokenSourcePool;
public TimeSpan Timeout { get; }
public Client(TimeSpan timeout)
{
this.Timeout = timeout;
this.timeoutTokenSourcePool = ObjectPool.Create<CancellationTokenSource>();
}
public async Task SendAsync()
{
var timeoutTokenSource = timeoutTokenSourcePool.Get();
timeoutTokenSource.CancelAfter(Timeout);
try
{
await SendCoreAsync(timeoutTokenSource.Token);
}
finally
{
// Not raised timeout, you can reuse by Reset
if (timeoutTokenSource.TryReset())
{
timeoutTokenSourcePool.Return(timeoutTokenSource);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment