Expanding on the answer by @Monsignor and the reply by @andrew-bennet, this is how I solved it:
- Leave the timeout of
HTTPClient
alone (100s by default) or set it up to anything larger than you will ever need, since it cannot be changed.
- Make all the calls using
HTTPClient
with a custom CancellationToken
with your desired timeout.
public class RestService : IRestService
{
protected readonly HttpClient Client;
protected static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
public async Task<T> GetAsync<T>(string uri, TimeSpan? customTimeOut = null)
{
[...]
CancellationToken cancellationToken = GetCancellationToken(customTimeOut);
try
{
response = await Client.GetAsync(uri, cancellationToken);
}
[...]
return result;
}
[...]
private static CancellationToken GetCancellationToken(TimeSpan? customTimeOut)
{
CancellationTokenSource cts = customTimeOut.HasValue
? new CancellationTokenSource(customTimeOut.Value)
: new CancellationTokenSource(DefaultTimeout);
CancellationToken cancellationToken = cts.Token;
return cancellationToken;
}
}
Perhaps you could reuse the CancellationTokenSource
, but I didn't want to complicate the sample further.
Timeout
is used to setCancelAfter
on theCancellationTokenSource
before the async task is started (internally). So, even if you could change it afterwards, through some "trick", it would have no effect. – Supersession