27.6 Parallel的靜態For,Foreach和Invoke方法
阿新 • • 發佈:2018-12-31
ons cat ota index () lose mas exc adk
static void Main(string[] args) { //for (int i = 0; i < 10000; i++) // DoWork(i); //Parallel.For(0, 10000, i => DoWork(i)); //Mehtod1(); //Mehtod2(); //Mehtod3(); Parallel.Invoke(() => Mehtod1(), () => Mehtod2(), () => Mehtod3()); Console.ReadKey(); }private static void DoWork(int a) { Console.WriteLine(a); } private static void Mehtod1() { Console.WriteLine("Mehtod1"); } private static void Mehtod2() { Console.WriteLine("Mehtod2"); }private static void Mehtod3() { Console.WriteLine("Mehtod3"); }
static void Main(string[] args) { var a = DirectoryBytes(@"I:\BaiduNetdiskDownload", "*.*", SearchOption.AllDirectories); Console.ReadKey(); }private static long DirectoryBytes(string path, string searchPattern, SearchOption searchOption) { var files = Directory.EnumerateFiles(path, searchPattern, searchOption); long masterTotal = 0; ParallelLoopResult result = Parallel.ForEach<string, long>(files, () => { return 0; /*每個任務開始前,總計值都初始化為0*/}, (file, loopState, index, taskLocalTotal) => { long fileLength = 0; FileStream fs = null; try { fs = File.OpenRead(file); fileLength = fs.Length; } catch (Exception) {/*忽略拒絕訪問過得文件*/ } finally { if (fs != null) fs.Close(); } return taskLocalTotal += fileLength; }, taskLocalTotal => { Interlocked.Add(ref masterTotal, taskLocalTotal); } ); return masterTotal; }
27.6 Parallel的靜態For,Foreach和Invoke方法