I don’t know if it’s correct to ask such questions on this site ... In general, I’m not sure that the code below is correctly written. He performs his task, checked repeatedly. However, I have doubts about how this implementation can be considered correct. Perhaps on C # this kind of task can be implemented differently? I would like to receive criticism and clarification.
The program itself is an audio converter. It searches for suitable files in the folder and launches an external, console converter to convert them to wav.
public partial class Form1 : Form { static object locker = new object(); string[] findFiles; int fifi = -1; public Form1() { InitializeComponent(); Conv(); { async void Conv() { findFiles = Directory.GetFiles(Application.StartupPath, "*.ape", SearchOption.AllDirectories).Union(Directory.GetFiles(Application.StartupPath, "*.ogg", SearchOption.AllDirectories)).ToArray(); // Поддерживаем не более 8 ядер. int p; if (Environment.ProcessorCount < 8) p = Environment.ProcessorCount; else p = 8; int t; // Если количество файлов больше чем ядер, то устанавливаем столько потоков, сколько ядер. if(findFiles.Length > p) t = p; else // Если файлов меньше чем ядер, то потоков устанавливаем сколько файлов. t = findFiles.Length; // Устанавливаем количество потоков. Task[] tasks = new Task[t]; // Запускаем потоки. for (int i = 0; i <= p - 1; i++) { if(i <= findFiles.Length - 1) { tasks[i] = new Task(() => ConvertDoWork(++fifi)); tasks[i].Start(); } } // Ждём выполнения всех задач. await TaskEx.WhenAll(tasks); Application.Exit(); } int p, pc; public void ConvertDoWork(int num) { int n = num; if ((findFiles.Length == 0) || (n > findFiles.Length)) return; string s = findFiles[n]; ProcessStartInfo startInfo = new ProcessStartInfo(); if (Path.GetExtension(s).Equals(".ogg")) { startInfo.FileName = "oggdec.exe"; startInfo.Arguments = "-Q \"" + s + "\""; } else if (Path.GetExtension(s).Equals(".ape")) { startInfo.FileName = "MAC.exe"; startInfo.Arguments = "\"" + s + "\" \"" + Path.ChangeExtension(s, ".wav") + "\" -d"; } startInfo.WorkingDirectory = Application.StartupPath; startInfo.CreateNoWindow = true; Process processReg = new Process(); processReg.StartInfo = startInfo; processReg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; processReg.Start(); processReg.WaitForExit(); lock (locker) File.Delete(s); int percentComplete = (int)Math.Round((double)(100 * n) / findFiles.Length); pc = percentComplete / 10; try { this.Invoke((MethodInvoker)delegate { progressBar1.Value = percentComplete; // Если не выбрано не отображать прогресс, то отображаем всплывашку. if ((notifyIcon1.Visible) && (!chkNotNotify.Checked) && (!pc.Equals(p))) { notifyIcon1.ShowBalloonTip(300, "Прогресс", "Выполнено " + percentComplete + "% работы", ToolTipIcon.Info); p = pc; } }); } catch (System.Exception ex) { } lock (locker) ++fifi; if (fifi < findFiles.Length) ConvertDoWork(fifi); }
Directory.EnumerateFiles(@"c:\media\", "sound*.mp3").AsParallel().ForAll(file => { ... });- An example here - Stack