zoukankan      html  css  js  c++  java
  • C#异步编程のParallel(并行)

    Parallel是循环中开启多线程

    Stopwatch watch1 = new Stopwatch();
    watch1.Start();
    for (int i = 1; i <= 10; i++)
    {
        Console.Write(i + ",");
        Thread.Sleep(1000);
    }
    watch1.Stop();
    Console.WriteLine(watch1.Elapsed);
    
    Stopwatch watch2 = new Stopwatch();
    watch2.Start();
    
    //会调用线程池中的线程
    Parallel.For(1, 11, i =>
    {
        Console.WriteLine(i + ",线程ID:" + Thread.CurrentThread.ManagedThreadId);
        Thread.Sleep(1000);
    });
    watch2.Stop();
    Console.WriteLine(watch2.Elapsed);
    

      循环List<T>

    List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 6, 7, 8, 9 };
    Parallel.ForEach<int>(list, n =>
    {
        Console.WriteLine(n);
        Thread.Sleep(1000);
    });

    循环Action[]
    Action[] actions = new Action[] { 
       new Action(()=>{
           Console.WriteLine("方法1");
       }),
        new Action(()=>{
           Console.WriteLine("方法2");
       })
    };
    Parallel.Invoke(actions);
  • 相关阅读:
    (一)Sturts2概述
    day18,常用的模块,os,sys...等
    day17,模块的导入
    day16
    day15
    day14
    day13
    day12
    day11
    day10
  • 原文地址:https://www.cnblogs.com/xietianjiao/p/7429849.html
Copyright © 2011-2022 走看看