更改默认超时 [英] Change default timeout

查看:69
本文介绍了更改默认超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下实现.默认超时为100秒.

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()))
        {

        }
    }
 }

推荐答案

HttpClient的默认超时为 HttpClient超时

您可以调整到HttpClient并在HttpService内部设置自定义超时时间.

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

httpClient.Timeout = 5000;

HttpClient请求超时

您也可以通过取消令牌 CancellationTokenSource

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);
}


一些注意事项:

  1. HttpService内部进行更改将影响所有请求.如果要根据请求进行设置,则需要将所需的超时时间作为参数传递.
  2. 如果CancellationTokenSource的超时时间小于HttpClient设置的Timeout并且HttpClient的超时时间不是无限的,则传递CancellationTokenSource的实例将起作用.否则,HttpClient的超时将发生.
  1. 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. Passing an instance of CancellationTokenSource will work if it's timeout is lower than Timeout set by the HttpClient and HttpClient's timeout is not infinite. Otherwise, the HttpClient's timeout will take place.

这篇关于更改默认超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆