并行

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;



namespace MoreThread

{

    internal class Program

    {

        private static void Main(string[] args)

        {

            TestParallelFor t1 = new TestParallelFor();

            t1.DoSomeThing();

            TestParallelForEach t2 = new TestParallelForEach();

            t2.DoSomeThing();

            Console.ReadKey();

        }

    }



    public interface ITestThread

    {

        void DoSomeThing();

    }



    public class TestParallelFor : ITestThread

    {

        private int GetData(int i)

        {

            Thread.Sleep(1000);

            return i;

        }



        public void DoSomeThing()

        {

            DateTime dt = DateTime.Now;

            Console.WriteLine("开始执行时间:" + DateTime.Now.ToString());

            List<int> list = new List<int>();

            System.Threading.Tasks.Parallel.For(0, 10, (i) =>

            {

                list.Add(GetData(i));

            });

            Console.WriteLine("TestParallelFor-" + (DateTime.Now - dt).TotalMilliseconds.ToString() + "毫秒");

            Console.WriteLine("结束执行时间:" + DateTime.Now.ToString());

            list.ForEach(x =>

            {

                Console.WriteLine(x);

            });

        }

    }



    public class TestParallelForEach : ITestThread

    {

        private int GetData(int i)

        {

            Console.WriteLine("I=" + i.ToString());

            Thread.Sleep(1000);

            return i;

        }



        public void DoSomeThing()

        {

            DateTime dt = DateTime.Now;

            Console.WriteLine("开始执行时间:" + DateTime.Now.ToString());

            List<int> list = new List<int>();

            List<int> list2 = new List<int>();

            for (int i = 0; i < 10; i++)

            {

                list2.Add(i);

            }

            System.Threading.Tasks.Parallel.ForEach(list2, (i) =>

            {

                list.Add(GetData(i));

            });

            list.ForEach(x =>

            {

                Console.WriteLine(x);

            });

            Console.WriteLine("TestParallelForEach-" + (DateTime.Now - dt).TotalMilliseconds.ToString() + "毫秒");

            Console.WriteLine("结束执行时间:" + DateTime.Now.ToString());

        }

    }

}

并行

 

你可能感兴趣的:(并行)