Nikita Goncharuk
Nikita Goncharuk

Reputation: 815

Handle a long download time

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?

Upvotes: 0

Views: 60

Answers (1)

Nikita Goncharuk
Nikita Goncharuk

Reputation: 815

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
}

Upvotes: 2

Related Questions