gpt4 book ai didi

c# - 在 c# httpclient 上设置超时不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 14:44:04 28 4
gpt4 key购买 nike

我将超时设置为 1 毫秒,但是当我测试时,所有的 http 调用似乎都工作正常,几乎就像它忽略了超时一样。如何让它发挥作用?

谢谢

    private static HttpClient client = new HttpClient()
{
Timeout = TimeSpan.FromMilliseconds(1)
}; // re-use the object

/// <summary>
/// Make a GET call.
/// </summary>
public static async Task<string> GetAsync(string uri, string token_type, string access_token, string accept, string content_type)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
if (content_type != null) request.Headers.TryAddWithoutValidation("Content-Type", content_type);
if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); // ACCEPT header
if (token_type != null && access_token != null) request.Headers.Authorization = new AuthenticationHeaderValue(token_type, access_token);
HttpResponseMessage g = await client.SendAsync(request);

if (g.IsSuccessStatusCode)
{
return await g.Content.ReadAsStringAsync();
}
else
{
throw new ExternalException(await g.Content.ReadAsStringAsync(), (int)g.StatusCode);
//throw new ExternalException(await g.Content.ReadAsStringAsync() + " Reason: " + g.ReasonPhrase + " Message: " + g.RequestMessage + " Status Code: " + g.StatusCode + " Token Type: " + token_type + " Content Type: " + content_type + " Accept: " + accept, (int)g.StatusCode);
}
}

/// <summary>
/// Make a POST call. The content type should be embedded in the postData already.
/// </summary>
public static async Task<string> PostAsync(string uri, string token_type, string access_token, HttpContent postData, string accept)
{
string mes = await postData.ReadAsStringAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri)
{
Content = postData // CONTENT-TYPE header
};

if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); // ACCEPT header
if (token_type != null && access_token != null) request.Headers.Authorization = new AuthenticationHeaderValue(token_type, access_token);
HttpResponseMessage g = await client.SendAsync(request);

if (g.IsSuccessStatusCode)
{
return await g.Content.ReadAsStringAsync();
}
else
{
throw new ExternalException(await g.Content.ReadAsStringAsync(), (int)g.StatusCode);
//throw new ExternalException(await g.Content.ReadAsStringAsync() + " Reason: " + g.ReasonPhrase + " Message: " + g.RequestMessage + " Status Code: " + g.StatusCode + " Token Type: " + token_type + " Post Data: " + mes + " Accept: " + accept, (int)g.StatusCode);
}
}

最佳答案

问题是,这段代码是在后台线程上执行的。如果您从不等待它(通过显式等待,或在某处获取“结果”等),异常本身将在后台线程中被忽略(成为未处理的异常)。当然,您应该通过在某个时间点获取结果(或等待)来防止这种情况发生。在您的情况下,您可以像这样使用它:

GetAsync.Wait();

这将为您抛出异常。

关于c# - 在 c# httpclient 上设置超时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55305784/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com