gpt4 book ai didi

c# - 如何减少尝试执行请求的时间?

转载 作者:太空宇宙 更新时间:2023-11-03 22:34:18 24 4
gpt4 key购买 nike

我正在使用 gmail api 并尝试获取消息数。如果 Internet 连接出现问题 Execute() 尝试执行超过 1 分钟。我想在 5 秒无响应后跳过执行,不再等待。

var getEmailsRequest = new UsersResource.MessagesResource.ListRequest(service, userId);
try
{
messagesCount = getEmailsRequest.Execute().Messages.Count;
}
catch (TaskCanceledException ex)
{
//after more than minute of waiting with no connection I can catch this exception
}

最佳答案

免责声明:我对相关图书馆一无所知;-)


如果您使用 googleapis/google-api-dotnet-client :

然后你应该能够用 this 配置超时:

/// <summary> 
/// HTTP client initializer for changing the default behavior of HTTP client.
/// Use this initializer to change default values like timeout and number of tries.
/// You can also set different handlers and interceptors like
/// <see cref="IHttpUnsuccessfulResponseHandler"/>s,
/// <see cref="IHttpExceptionHandler"/>s and <see cref="IHttpExecuteInterceptor"/>s.
/// </summary>
public interface IConfigurableHttpClientInitializer
{
/// <summary>Initializes a HTTP client after it was created.</summary>
void Initialize(ConfigurableHttpClient httpClient);
}

作为替代方案,您可以将 ExecuteAsync 与取消 token 一起使用,例如:

CancellationTokenSource source = 
new CancellationTokenSource(TimeSpan.FromMilliseconds(5000));

var someResult = await getEmailsRequest.ExecuteAsync(source.Token);
messagesCount = someResult.Messages.Count;

请注意,要使其正常工作,您需要一个 async Task 作为方法签名。

关于c# - 如何减少尝试执行请求的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55911599/

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