RestSharp超时无法正常工作

Mil*_*vic 7 .net c# windows-services timeout restsharp

我有一个restsharp客户端和请求设置如下:

var request = new RestRequest();
request.Method = Method.POST;
request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.Timeout = -1;
request.ReadWriteTimeout = -1;
var url = $"http://{ipAddress}/api/calculate";
var client = new RestClient();
client.BaseUrl = new Uri(url);
client.Timeout = -1;
client.ReadWriteTimeout = -1;
var response = client.Execute(request);
Run Code Online (Sandbox Code Playgroud)

这个请求需要一段时间才能完成,大约需要30分钟.现在,我知道有更优雅的方法可以做到这一点,但是,对于这个请求,我需要这样做.

此RestSharp客户端和请求在Windows服务中执行.当服务执行请求时,它会抛出TimoutException并且请求最大超时大约为40秒.

出于某种原因,我设置的超时对于这种情况不起作用.

有人有解决方案吗?

Ken*_*ain 13

您可能无法通过设置ReadWriteTimeout值来执行您认为的操作.您的值将被忽略,因此您将获得默认值.

根据这个答案,什么是RestSharp RestClient的默认超时值?RestSharp HttpWebRequest在其实现中使用.

超时属性HttpWebRequest不能为负HttpWebRequest.Timeout属性.

如果你查看RestSharp客户端代码,你会看到:https://github.com/restsharp/RestSharp/blob/70de357b0b9dfc3926c95d1e69967c7a7cbe874c/RestSharp/RestClient.cs#L452

        int readWriteTimeout = request.ReadWriteTimeout > 0
            ? request.ReadWriteTimeout
            : this.ReadWriteTimeout;

        if (readWriteTimeout > 0)
        {
            http.ReadWriteTimeout = readWriteTimeout;
        }
Run Code Online (Sandbox Code Playgroud)

  • 首先,我会将操作分解为开始、状态和结果操作。拨打电话,返回令牌,然后检查状态。最后得到保存的结果。如果那不可行,那么我建议尽可能长时间地超时并希望最好。如果您控制了 API,那么就去寻找 1 号门后的东西。 (2认同)

BKS*_*eon 5

如何更改默认超时时间长度:

将默认超时更改为:5秒-例如-(即5000毫秒):

    var client = new RestClient(BaseUrl);
    client.Timeout = 5000; // 5000 milliseconds == 5 seconds
Run Code Online (Sandbox Code Playgroud)

就是这样,希望对您有所帮助!


Ram*_* A. 5

更新至 RestSharp v106.2.2。
请参阅https://github.com/restsharp/RestSharp/issues/1093