private void DumpStartingInfo(OperationParameters operationParameters) { var strBuilder = new StringBuilder(); strBuilder.AppendLine("Starting Operation:"); strBuilder.AppendLine($"\tNumber Of Files: {operationParameters.ImagesPathsList.Count}"); strBuilder.AppendLine($"\tOutput Path: {operationParameters.OutputPath}"); strBuilder.AppendLine($"\tMax Size: {operationParameters.MaxSize} {operationParameters.MaxSizeType.ToString()}"); LogMessage(strBuilder.ToString()); }
private async void btnStart_Click(object sender, EventArgs e) { txtLog.Clear(); if (_imagesPathsList == null) { LogMessage("No Files Selected"); return; } var maxSize = -1; if (!int.TryParse(txtMaxSize.Text, out maxSize)) { LogMessage("No Valid Size"); return; } if (string.IsNullOrWhiteSpace(txtOutput.Text)) { LogMessage("No Output Path Chosen"); return; } // setting up operation parameters _operationParameters = new OperationParameters { ImagesPathsList = _imagesPathsList, OutputPath = txtOutput.Text, MaxSize = maxSize, MaxSizeType = comboSizeType.SelectedIndex == 0 ? SizeType.Megabytes : comboSizeType.SelectedIndex == 1 ? SizeType.Kilobytes : SizeType.Bytes, ImageType = comboImageType.SelectedIndex == 0 ? ImageType.Png : ImageType.Jpg, }; DumpStartingInfo(_operationParameters); if (!Directory.Exists(_operationParameters.OutputPath)) { Directory.CreateDirectory(_operationParameters.OutputPath); } // canceling previous operation _cancellationTokenSource?.Cancel(); _cancellationTokenSource = new CancellationTokenSource(); // preparing the progress bar _context = SynchronizationContext.Current; progressBar.Minimum = 0; progressBar.Maximum = _imagesPathsList.Count; progressBar.Value = 0; // defining the action block to use var proccessImageBlock = new ActionBlock <string>((path) => { ProccessImage(path); _context.Send((_) => { progressBar.Value++; }, null); GC.Collect(); }, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = _cancellationTokenSource.Token, }); btnStart.Enabled = false; btnCancel.Enabled = true; Parallel.ForEach(_imagesPathsList, (path) => { proccessImageBlock.Post(path); }); // finish submitting and wait for completion proccessImageBlock.Complete(); await proccessImageBlock.Completion.ContinueWith(task => { _context.Send((_) => { LogMessage("Done"); btnStart.Enabled = true; btnCancel.Enabled = false; }, null); }); }