應用程式所建立的每個 HTTP 連線都會造成一定程度的負擔。這個程式庫支援批次處理,可讓應用程式在單一 HTTP 要求中加入多個 API 呼叫。您可能想要使用批次處理的情況範例:
- 您要提出許多小型要求,想要降低 HTTP 要求的負擔。
- 使用者在應用程式離線時變更了資料,因此您的應用程式必須傳送大量更新及刪除內容,藉此同步處理本機資料與伺服器。
注意:單一批次要求中最多只能有 1,000 次呼叫。如果您需要進行更多的呼叫,請使用多個批次要求。
注意:您無法在批次要求中使用媒體上傳物件。
詳細說明
如要建立批次要求,您可以將 BatchRequest
物件執行個體化,然後針對要執行的每個要求呼叫 Queue
方法。透過每個要求,請傳入應用程式收到要求的回應時要呼叫的回呼。回呼函式的引數如下:
- 內容
- 內容回應;如果要求失敗,則為
null
。 - 錯誤
- 錯誤;如果要求成功,則傳回
null
。 - index
- 個別要求的索引。
- 訊息
- 包含所有標頭和內容的完整 HTTP 訊息。
ExecuteAsync
方法來提出要求。
在下列程式碼片段中,系統會將兩個 API 要求批次處理為單一 HTTP 要求,並為每個 API 要求提供回呼:
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();