zoukankan      html  css  js  c++  java
  • 一个简单示例看懂.Net 并行编程

    此示例尽量以最简洁的代码演示并行处理的功能,此示例代码中分别用单线程和多线程分别执行5次耗时1秒的操作。打印出执行过程及耗时。

    以下为示例代码,.net framework要求4.0以上。

    using System;
    using System.Collections.Generic;
    using System.Collections.Concurrent;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ParallelDemo
    {
    
        class Program
        {
            static void Main(string[] args)
            {
                // First do the sequential version.
                Console.WriteLine("Executing sequential loop...");
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
    
    //单线程执行
    for (int i = 0; i < 5; i++) { TestMethod(); } stopwatch.Stop(); Console.WriteLine("Sequential loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds); // Reset timer and results matrix. stopwatch.Reset(); Console.WriteLine("Executing parallel loop..."); stopwatch.Start();
    //多线程执行 Parallel.For(
    0, 5, i => TestMethod()); stopwatch.Stop(); Console.WriteLine("Parallel loop time in milliseconds: {0}", stopwatch.ElapsedMilliseconds); // Keep the console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } static void TestMethod() { var tid = Thread.CurrentThread.ManagedThreadId; Console.WriteLine("Thread {0} start", tid); Thread.Sleep(1000); Console.WriteLine("Thread {0} end", tid); } } }

    运行结果

    Executing sequential loop...
    Thread 9 start
    Thread 9 end
    Thread 9 start
    Thread 9 end
    Thread 9 start
    Thread 9 end
    Thread 9 start
    Thread 9 end
    Thread 9 start
    Thread 9 end
    Sequential loop time in milliseconds: 5004
    Executing parallel loop...
    Thread 9 start
    Thread 10 start
    Thread 11 start
    Thread 12 start
    Thread 13 start
    Thread 9 end
    Thread 10 end
    Thread 11 end
    Thread 12 end
    Thread 13 end
    Parallel loop time in milliseconds: 1024
    Press any key to exit.
    

    附:官方示例

  • 相关阅读:
    问题2 机器学习篇 正则化L1和L2有什么区别?
    numpy 数组拼接方法
    问题1 机器学习篇 如何解决过拟合(overfiting)?
    低阶 TensorFlow 基础知识
    k-Nearest Neighbors 实战2 使用kNN算法改进约会网站的配对结果
    k-Nearest Neighbors 实战1 简单的电影分类实例
    VirtualBox使用
    知乎登录设计思考
    微信返回上一页停留在上次点击的位置
    好的网站-一直在收集
  • 原文地址:https://www.cnblogs.com/icoolno1/p/6913100.html
Copyright © 2011-2022 走看看