Change default timeout

2019-06-27 07:54发布

问题:

I have the following implementation. And the default timeout is 100 seconds.

I wonder how can I able to change the default timeout?

HttpService.cs

public class HttpService : IHttpService
{

   private static async Task GoRequestAsync<T>(string url, Dictionary<string, object> parameters, HttpMethod method,
        Action<T> successAction, Action<Exception> errorAction = null, string body = "")
        where T : class
    {
        using (var httpClient = new HttpClient(new HttpClientHandler()))
        {

        }
    }
 }

回答1:

The default timeout of an HttpClient is 100 seconds.


HttpClient Timeout

You can adjust on your HttpClient and set a custom timeout duration inside of your HttpService.

httpClient.Timeout = 5000;


HttpClient Request Timeout

You could alternatively define a timeout via a cancellation token CancellationTokenSource

using (var cts = new CancellationTokenSource(new TimeSpan(0, 0, 5))
{
    await httpClient.GetAsync(url, cts.Token).ConfigureAwait(false);
}

Note, making changes inside of the HttpService will affect all requests. If you want to make it per request you will need to pass through your desired timeout duration as a parameter.



回答2:

Since we don't see any task created with a timeout i cannot help.

But if you are using a System.Net.Http under the hood of your application than MSDN says:

The default value is 100,000 milliseconds (100 seconds).

You can than change the value of the HttpClient.Timeout property

clent.Timeout = 5*1000;