您的位置:首页 > 其它

.NET4中多线程并行方法Parallel.ForEach

2017-07-15 14:20 190 查看
原文发布时间为:2011-12-10 —— 来源于本人的百度文章 [由搬家工具导入]

namespace ForEachDemo
{
    using System;
    using System.IO;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Linq;
    using System.Diagnostics;

    class SimpleForEach
    {
        static void Main()
        {
            // A simple source for demonstration purposes. Modify this path as necessary.
            var watch = new Stopwatch();
            var list = Enumerable.Range(0, 10);

            //  Method signature: Parallel.ForEach(IEnumerable<TSource> source, Action<TSource> body)
            watch.Start();
            Parallel.ForEach(list, item =>
            {
                try
                {
                    var t = 2 / item;
                    Console.WriteLine("Processing {0} on thread {1}", item,
                                        Thread.CurrentThread.ManagedThreadId);
                }
                catch
                {

                }

            } //close lambda expression
                 ); //close method invocation

            watch.Stop();
            Console.WriteLine(watch.ElapsedMilliseconds);
            // Keep the console window open in debug mode.
            Console.WriteLine("Processing complete. Press any key to exit.");
            Console.ReadKey();
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: