0

I sent a request to server using HttpClient, how can I limit the boot time, for example, 30 seconds?

Here is my method:

private async Task<HttpResponseMessage> SendRequestAsync(HttpRequestMessage request)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    return await client.SendAsync(request);
                }
            }
            catch (ArgumentNullException e)
            {
                Console.WriteLine(e.Message);
                throw new HttpRequestException();
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
                throw new HttpRequestException();
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new HttpRequestException();
            }
        }

How can i limit download time?

Nikita Goncharuk
  • 795
  • 1
  • 8
  • 23
  • 1
    Might be you are looking like: https://stackoverflow.com/a/11191070/7124761 – Prashant Pimpale Jun 27 '18 at 05:38
  • https://msdn.microsoft.com/en-us/library/system.net.http.httpclient.timeout(v=vs.110).aspx – mjwills Jun 27 '18 at 05:38
  • Possible duplicate of [Asynchronously wait for Task to complete with timeout](https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout) – Alex Riabov Jun 27 '18 at 05:42

1 Answers1

2

Here is solution:

int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else { 
    // timeout logic
}
Nikita Goncharuk
  • 795
  • 1
  • 8
  • 23