Last active
August 3, 2022 08:32
-
-
Save neuecc/134a1d3588f27965e4e6b604bd19d571 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
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