Search code examples
c#gmail-api

How to decrease time of request tried to get executed?


I'm using gmail api and trying to get count of messages. If problems with internet connection happens Execute() trying to get executed more than 1 minute. I want to skip executing after 5 seconds without response and not wait anymore.

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
}

Solution

  • Disclaimer: I know nothing of the library in question ;-)


    If you are using googleapis/google-api-dotnet-client :

    Then your should be able to configure a timeout with 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);
    }
    

    As alternative, you can use ExecuteAsyncwith the cancelation token, e.g.:

    CancellationTokenSource source = 
                 new CancellationTokenSource(TimeSpan.FromMilliseconds(5000));
    
    var someResult = await getEmailsRequest.ExecuteAsync(source.Token);
    messagesCount = someResult.Messages.Count;
    

    Do note, for this to work you need an async Task as method signature.