C# 多線程編程 – 使用委託建立線程

來源:互聯網
上載者:User

進程和線程

進程:進程包含資源,例如windows控制代碼,檔案系統控制代碼或者其他核心對象,每個進程都分配了虛擬記憶體。一個進程至少包含一個線程。作業系統會調度線程。

進程管理的資源套件括虛擬記憶體和windows控制代碼。

 

線程: 都有自己的堆棧,但程式碼的記憶體和堆由一個進程內所有的線程共用。

 

在.NET中,託管的線程由Thread類定義。託管的線程不一定映射為一個作業系統線程。

 

使用委託建立線程的三種方法

1. Pooling 投票方式

2. WaitHandle 等待控制代碼

3. Asynchronous Call 非同步回調

// 非同步委託樣本// Herbert// 個人學習使用using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Diagnostics;namespace AsyDelegate{    class Program    {        public delegate int TakesAWhileDelegate(int data, int ms);        static int TakesAWhile(int data, int ms)        {            Console.WriteLine("TakesAWhile started");            Thread.Sleep(ms);            Console.WriteLine("TalesAWhile completed");            return ++data;         }        public static void Method1()        {            // 第一種投票方式            // synchronouse method call            // TakesAWhile(1, 3000)            // Asynchronous by using a delegate            // IAsyncResult 可以獲得委託資訊,並驗證委託是否完成了任務            TakesAWhileDelegate dl = TakesAWhile;            IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null);            while (!ar.IsCompleted)            {                // do something else in the main thread                Console.Write(".");                Thread.Sleep(50);            }            int result = dl.EndInvoke(ar);            Console.WriteLine("result: {0}", result);                  }        public static void Method2()        {            // 第二種等待控制代碼方式                        // synchronouse method call            // TakesAWhile(1, 3000)            // Asynchronous by using a delegate            // WaitOne()將一個逾時時間作為可選的第一個參數,定義要等待的最大時間            TakesAWhileDelegate dl = TakesAWhile;            IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null);            while (true)            {                // do something else in the main thread                Console.Write(".");                if (ar.AsyncWaitHandle.WaitOne(50, false))                {                    Console.WriteLine("Can get the result now");                    break;                }            }            int result = dl.EndInvoke(ar);            Console.WriteLine("result: {0}", result);                   }        public static void TakesAWhileCompleted(IAsyncResult ar)        {            // 第三種方式非同步回調            if (ar == null)                throw new ArgumentNullException("ar");            TakesAWhileDelegate d1 = ar.AsyncState as TakesAWhileDelegate;            Trace.Assert(d1 != null, "Invalid object type");            int result = d1.EndInvoke(ar);            Console.WriteLine("result : {0}", result);         }        static void Main(string[] args)        {            Stopwatch sw1 = new Stopwatch();            Console.WriteLine("Method 1 Pooling started:");            sw1.Start();            Program.Method1();            sw1.Stop();            Console.WriteLine(sw1.ElapsedMilliseconds.ToString());            Stopwatch sw2 = new Stopwatch();            Console.WriteLine("Method 2 Wait Handler started:");            sw2.Start();            Program.Method2();            sw2.Stop();            Console.WriteLine(sw2.ElapsedMilliseconds.ToString());            Stopwatch sw3 = new Stopwatch();            Console.WriteLine("Method 3 Asynchronize CallBack started:");            sw3.Start();            TakesAWhileDelegate d1 = TakesAWhile;                        /*            d1.BeginInvoke(1, 3000, ar =>             {                int result = d1.EndInvoke(ar);                Console.WriteLine("result: {0}", result);            }), null;             */             d1.BeginInvoke(1, 3000, TakesAWhileCompleted, d1);            for (int i = 0; i < 100; i++)            {                Console.Write(".");                Thread.Sleep(50);            }            Console.WriteLine(sw3.ElapsedMilliseconds.ToString());            Console.ReadKey();                    }    }}

 

通過已耗用時間進行比較, 投票方式和非同步回調比較好用,似乎投票方式效率會低些,而非同步回調效率最高。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.