一個簡單樣本看懂.Net 並行編程

來源:互聯網
上載者:User

標籤:dmi   using   for   main   oid   功能   color   []   star   

此樣本盡量以最簡潔的代碼示範平行處理的功能,此範例程式碼中分別用單線程和多線程分別執行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 startThread 9 endThread 9 startThread 9 endThread 9 startThread 9 endThread 9 startThread 9 endThread 9 startThread 9 endSequential loop time in milliseconds: 5004Executing parallel loop...Thread 9 startThread 10 startThread 11 startThread 12 startThread 13 startThread 9 endThread 10 endThread 11 endThread 12 endThread 13 endParallel loop time in milliseconds: 1024Press any key to exit.

附:官方樣本

 

一個簡單樣本看懂.Net 並行編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.