首页 > 其他 > 详细

27.6 Parallel的静态For,Foreach和Invoke方法

时间:2018-12-30 22:43:22      阅读:180      评论:0      收藏:0      [点我收藏+]

 

        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方法

原文:https://www.cnblogs.com/kikyoqiang/p/10200937.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!