public void Children(int folderRequestId, string folder, Dispatcher dispatch, Func <int, FileEntry, int, bool> addEntry) { numFilesBeingFetched = 0; ChildrenResource.ListRequest request = _service.Children.List(folder); do { try { ChildList children = request.Fetch(); var expectedCount = children.Items.Count(); foreach (ChildReference child in children.Items) { do { lock (_thumbDownloaders) { if (_thumbDownloaders.Count < 12) { break; } } System.Threading.Thread.Sleep(100); } while (true); var doContinue = true; dispatch.Invoke( new Action(() => { doContinue = addEntry(expectedCount, null, folderRequestId); })); if (!doContinue) { break; } do { lock (this) { if (numFilesBeingFetched < 20) { break; } } System.Threading.Thread.Sleep(100); } while (true); FilesResource.GetRequest getReq = _service.Files.Get(child.Id); ++numFilesBeingFetched; getReq.FetchAsync((LazyResult <Google.Apis.Drive.v2.Data.File> response) => { --numFilesBeingFetched; Google.Apis.Drive.v2.Data.File file = response.GetResult(); doContinue = true; dispatch.Invoke( new Action(() => { doContinue = addEntry(expectedCount, null, folderRequestId); })); if (!doContinue) { return; } //download thumbnail if (file.ThumbnailLink != null) { if (_thumbCache.ContainsKey(file.Id)) { dispatch.BeginInvoke(new Action(() => { addEntry(expectedCount, new FileEntry(file, _thumbCache[file.Id], file.AlternateLink), folderRequestId); })); } else { TaskCompletionSource <byte[]> thumbTaskSrc = null; lock (_thumbDownloaders) { thumbTaskSrc = DownloadThumb(file.ThumbnailLink); _thumbDownloaders.Add(thumbTaskSrc); } thumbTaskSrc.Task.ContinueWith( (Task <byte[]> thumbTask) => { if (thumbTask.Result != null) { dispatch.BeginInvoke(new Action(() => { var thumb = new BitmapImage(); thumb.BeginInit(); thumb.StreamSource = new MemoryStream(thumbTask.Result); thumb.EndInit(); if (!_thumbCache.ContainsKey(file.Id)) { _thumbCache.Add(file.Id, thumb); } addEntry(expectedCount, new FileEntry(file, thumb, file.AlternateLink), folderRequestId); })); } else { //thumbnails may be absent dispatch.BeginInvoke(new Action(() => { addEntry(expectedCount, new FileEntry(file, GetFileIcon(file), file.AlternateLink), folderRequestId); })); } lock (_thumbDownloaders) _thumbDownloaders.Remove(thumbTaskSrc); }); } } else { dispatch.BeginInvoke(new Action(() => { addEntry(expectedCount, new FileEntry(file, GetFileIcon(file), file.AlternateLink), folderRequestId); })); } }); } request.PageToken = children.NextPageToken; } catch (Exception e) { Console.WriteLine("An error occurred: " + e.Message); request.PageToken = null; } var doContinue2 = true; dispatch.Invoke(new Action(() => { doContinue2 = addEntry(1, null, folderRequestId); //1 anything != 0 })); if (!doContinue2) { break; } } while (!String.IsNullOrEmpty(request.PageToken)); }