question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Started to get "A task was cancelled"

See original GitHub issue

I’ve noticed that i have started to get “A task was cancelled” errors from some tasks im using to collect data from GA. I have read this thread https://github.com/googleapis/google-api-dotnet-client/issues/1394 that looks similar but i don’t think i have any network issues. At least it fails both when i run it locally AND in my Azure function. It also doesn’t fail all the time, i use a loop to grab alot of data with something like X number of rows in each request. Sometimes it runs for 1 iteration, sometimes 3 and so on.

I suppose it is some kind of timeout error?

  • Is it possible to get any more details on the error than “A task was cancelled”? Can i enable more logging somehow?
  • What else can i do to debug this?

The gist of my code looks like this.

            while (rowcount >= maxResults && interations < maxIterations)
            {
                var accountEmailAddress = Environment.GetEnvironmentVariable("GA.AccountEmail");
                var api = new GoogleAnalyticsAPI(xmlKey, accountEmailAddress);

                string[] dimensions = new string[] { dimension };
                string[] metrics = new string[] { metric };
                string[] filters = new string[] { $"{pathFilter};{metric}>{viewFilter}" };
                string[] sort = new string[] { "-" + metric };

                log.LogInformation($"Start GA request for iteration {interations} of {maxIterations}.");

                var request = api.BuildAnalyticRequest("ga:15796540", dimensions, metrics, filters, maxResults, sort, startDate, endDate, index, "gaid::-1");

                var response = request.Execute();

                foreach (List<string> row in response.Rows)
                {
                    allRows.Add(row);
                }

                rowcount = response.Rows.Count;

                log.LogInformation($"Collected {rowcount} from GA in iteration {interations}.");

                index += rowcount;
                interations += 1;
            }
        public DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics,
                                                                    string[] filters, int maxResults, string[] sort,
                                                                    string startDate, string endDate, int startIndex, string segment)
        {

            DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate,
                                                                                endDate, string.Join(",", metrics));
            request.Dimensions = string.Join(",", dimensions);
            request.MaxResults = maxResults;
            request.Filters = string.Join(",", filters);
            request.Sort = string.Join(",", sort);
            request.StartIndex = startIndex;
            if (segment != "")
            {
                request.Segment = segment;
            }

            return request;

        }
        public GoogleAnalyticsAPI(string xmlKey, string accountEmailAddress)
        {

            var rsa = new RSACryptoServiceProvider();
            RSACryptoServiceProviderExtensions.RSACryptoServiceProviderExtensions.FromXmlString(rsa, xmlKey);


            ServiceAccountCredential credentials = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(accountEmailAddress)
            {
                Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly },
                Key = rsa
            });

            Service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName = "WorthlessVariable"
            });
        }

When i started debugging this i was using Google.Apis.Analytics.v3 1.37.0.1306 but i updated it to 1.49.0.1679 but i still get the same error.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:10

github_iconTop GitHub Comments

6reactions
jskeetcommented, Dec 30, 2020

Thanks for the extra information, folks. It does sound like it’s probably something in the service itself - I’ll raise it internally on Tuesday.

3reactions
Robert-Zandbergcommented, Dec 29, 2020

We have currently the same issue (A task was cancelled).

We’re using the Service account method with an certificate. The code looks like this:

  var certificate2 = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
  var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(_gaMail)
  {
    Scopes = scopes
  }.FromCertificate(certificate2));

  var service = new AnalyticsService(new BaseClientService.Initializer
  {
    ApplicationName = "Analytics portal",
    HttpClientInitializer = credential
  });



  var dataList = _db.GaProperties.Where(property => property.Enabled).ToList();
  var dataAray = new GaSiteData[dataList.Count + 1];
  var total = 0;

  try
  {
    var data = service.Data.Realtime.Get("ga:" + dataList[0].PropertyId, "rt:activeUsers").Execute();
    var  gaVisitors = data.TotalsForAllResults["rt:activeUsers"];
    total += int.Parse(gaVisitors);
  }
  catch (GoogleApiException e)
  {
    var gaVisitors = "Error realtime api google";
  }

The error doesn’t show up all the time so my guess is that when I build the workaround that retries the failed request it will do the job.

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - HttpClient - A task was cancelled?
Disposing the HttpClient instance can cause following HTTP requests started by other instances of HttpClient to be cancelled!
Read more >
A task was canceled with IHttpClientFactory - Microsoft Q&A
A task was canceled with IHttpClientFactory ... Sometimes (not always) the code runs with the error above: System.Threading.Tasks.
Read more >
Task Cancellation
TaskCanceledException exception (wrapped in an AggregateException exception) is thrown. This exception indicates successful cancellation instead ...
Read more >
"A task was cancelled" exception sometimes thrown
Sometimes I'll see an exception thrown that tells me “A task was cancelled” when executing "Export-PowerBIReport" cmdlet. I did come across.
Read more >
"A Task was cancelled" exception in Blazor Server : r/csharp
Task being cancelled simply means your task timed out. Your db call is probably failing but not returning a failure, like if you...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found