RestSharp 超时不起作用

RestSharp Timeout not working

我有一个 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);

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

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

出于某种原因,我设置的超时不适用于这种情况。

有人对此有解决方案吗?

您设置 ReadWriteTimeout 值可能不是您所想的那样。您的值将被忽略,因此您将获得默认值。

根据这个答案 RestSharp 在其实现中使用 HttpWebRequest

HttpWebRequest 的超时 属性 不能为负值 HttpWebRequest.Timeout Property

如果您查看 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;
        }

版本 107+

var options = new RestClientOptions("baseURL") {
    ThrowOnAnyError = true,
    Timeout = 1000  // 1 second. or whatever time you want.
};
var client = new RestClient(options);

旧版本:

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

    var client = new RestClient(BaseUrl);
    client.Timeout = 5000; // 5000 milliseconds == 5 seconds

更新到 RestSharp v106.2.2。
参见 https://github.com/restsharp/RestSharp/issues/1093