Send Batch Requests

Each HTTP connection that your application makes results in a certain amount of overhead. This library supports batching, to allow your application to put several API calls into a single HTTP request. Examples of situations when you might want to use batching:

  • You have many small requests to make and would like to minimize HTTP request overhead.
  • A user made changes to data while your application was offline, so your application needs to synchronize its local data with the server by sending a lot of updates and deletes.

Note: You're limited to 1,000 calls in a single batch request. If you need to make more calls than that, use multiple batch requests.

Note: You cannot use a media upload object in a batch request.

Details

You create batch requests by instantiating a BatchRequest object and then calling the Queue method for each request you want to execute. With each request, pass in a callback to be called when your application receives the response to that request. The callback function's arguments are:

content
The content response, or null if the request failed.
error
The error, or null if the request succeeded.
index
The index of the individual request.
message
The full HTTP message that includes all its headers and content.
After you've added the requests, you call the ExecuteAsync method to make the requests.

In the following code snippet, two API requests are batched into a single HTTP request, and each API request is supplied a callback:

UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        new[] { CalendarService.Scope.Calendar },
        "user", CancellationToken.None, new FileDataStore("Calendar.Sample.Store"));
}

// Create the service.
var service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "Google Calendar API Sample",
    });

// Create a batch request.
var request = new BatchRequest(service);
request.Queue<CalendarList>(service.CalendarList.List(),
     (content, error, i, message) =>
     {
         // Put your callback code here.
     });
request.Queue<Event>(service.Events.Insert(
     new Event
     {
         Summary = "Learn how to execute a batch request",
         Start = new EventDateTime() { DateTime = new DateTime(2014, 1, 1, 10, 0, 0) },
         End = new EventDateTime() { DateTime = new DateTime(2014, 1, 1, 12, 0, 0) }
     }, "YOUR_CALENDAR_ID_HERE"),
     (content, error, i, message) =>
     {
         // Put your callback code here.
     });
// You can add more Queue calls here.

// Execute the batch request, which includes the 2 requests above.
await request.ExecuteAsync();