private void fetchEntireDataSetCompleted(Task task) { toggleBusyState(false); lblExportProgress.Text = "Download complete"; FetchFullDataSetContext context = (FetchFullDataSetContext)task.AsyncState; // cancel the scroll token Task.Factory.StartNew(() => { var conf = new ConnectionConfiguration(new Uri(ClusterUrl)); var client = new ElasticLowLevelClient(conf); var clearRequest = client.ClearScroll <dynamic>(new { scroll_id = new string[] { context.ScrollToken } }); }); bool process = task.Status == TaskStatus.RanToCompletion; if (task.Status == TaskStatus.Faulted) { MessageBox.Show($"Export has failed\r\n{task.Exception.Message}\r\n{task.Exception.InnerException?.Message}", Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } // Let user process data that has already been downloaded if ((task.Status == TaskStatus.Faulted || task.Status == TaskStatus.Canceled) && context.ProcessedDocuments > 0) { if (MessageBox.Show($"{context.ProcessedDocuments} documents were downloaded, would you like to still process those even though this is an incomplete export?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { process = true; } } if (process && sfdExportCSV.ShowDialog() == DialogResult.OK) { context.CSVFileName = sfdExportCSV.FileName; context.TotalDocuments = context.ProcessedDocuments; context.ProcessedDocuments = 0; if (cancellationToken != null) { cancellationToken.Dispose(); } cancellationToken = new CancellationTokenSource(); toggleBusyState(true); lblOperation.Text = "Merging..."; Task.Factory.StartNew(mergeDataSet, context, cancellationToken.Token).ContinueWith(mergeDataSetCompleted, TaskScheduler.FromCurrentSynchronizationContext()); } else { cleanContext(context); } }