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

How to decrease time of request tried to get executed?

我正在使用 gmail api 并尝试统计邮件数量。如果互联网连接出现问题 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 与取消标记一起使用,例如:

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

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

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