應用程式建立的每個 HTTP 連線都會造成一定程度的負擔。這個程式庫支援批次作業 ,讓應用程式在單一 HTTP 要求中加入多個 API 呼叫。 以下是您可能想使用批次處理的情況範例:
- 您需要發出許多小型要求,並希望盡可能減少 HTTP 要求的額外負擔。
- 使用者在您的應用程式離線時變更了資料, 所以應用程式需要將本機資料與伺服器同步 傳送大量更新和刪除資料
注意:單一批次要求最多只能有 1,000 個呼叫。 如果您需要進行更多呼叫,請使用多個批次要求。
注意:您無法使用 上傳媒體內容 將物件寫入批次要求中
詳細資料
如要建立批次要求,您可以將
BatchRequest
物件,然後針對您要執行的每個要求呼叫 Queue
方法。
針對每個要求,請傳入應用程式收到要呼叫的回呼。
用於回應該要求的回應
回呼函式的引數如下:
- 內容
- 內容回應,如果要求失敗則為
null
。 - 錯誤
- 錯誤,如果要求成功則為
null
。 - 索引
- 個別要求的索引。
- 訊息
- 包含所有標頭和內容的完整 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();