• 并行


    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());
            }
        }
    }

     
  • 相关阅读:
    ansible4:playbook介绍及使用
    ansible3:模块介绍
    Rabin加密算法
    基础业务:图片懒加载
    基础业务:滚动到指定位置导航固定(CSS实现)
    数据库事务处理的并发控制技术(二):事务模型
    详解HTTP缓存
    数据库事务处理的并发控制技术(一):并发控制概述
    二叉树的深度优先遍历和广度优先遍历
    Virtual DOM的简单实现
  • 原文地址:https://www.cnblogs.com/rhythmK/p/2700425.html
Copyright © 2020-2023  润新知