Я нашел здесь https://stackoverflow.com/a/19215782/4332018 хорошее решение для использования CancellationToken
с async HttpWebRequest
:
public static class Extensions
{
public static async Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request, CancellationToken ct)
{
using (ct.Register(() => request.Abort(), useSynchronizationContext: false))
{
try
{
var response = await request.GetResponseAsync();
return (HttpWebResponse)response;
}
catch (WebException ex)
{
// WebException is thrown when request.Abort() is called,
// but there may be many other reasons,
// propagate the WebException to the caller correctly
if (ct.IsCancellationRequested)
{
// the WebException will be available as Exception.InnerException
throw new OperationCanceledException(ex.Message, ex, ct);
}
// cancellation hasn't been requested, rethrow the original WebException
throw;
}
}
}
}
Но я не понимаю, как я могу прервать request
, если этовыполняется дольше установленного времени.
Я знаю о CancellationTokenSource()
и CancelAfter(Int32)
, но не понимаю, как изменить приведенный выше пример для использования CancellationTokenSource
, поскольку в нем нет Register
метода.
Как сделать async HttpWebRequest
с возможностью отмены по истечении заданного времени?