C#多線程 線程池

來源:互聯網
上載者:User

標籤:

執行個體1:直接看看微軟提供的代碼

using System;using System.Threading;public class Example{    public static void Main()    {        // Queue the task.        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));        Console.WriteLine("Main thread does some work, then sleeps.");        // If you comment out the Sleep, the main thread exits before        // the thread pool task runs.  The thread pool uses background        // threads, which do not keep the application running.  (This        // is a simple example of a race condition.)        Thread.Sleep(1000);        Console.WriteLine("Main thread exits.");    }    // This thread procedure performs the task.    static void ThreadProc(Object stateInfo)    {        // No state object was passed to QueueUserWorkItem, so         // stateInfo is null.        Console.WriteLine("Hello from the thread pool.");    }}

 

using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace Example{    class ThreadPoolDemo    {        // 用於儲存每個線程的計算結果        static int[] result = new int[10];        //注意:由於WaitCallback委託的聲明帶有參數,        //所以將被調用的Fun方法必須帶有參數,即:Fun(object obj)。        static void Fun(object obj)        {            int n = (int)obj;            //計算階乘            int fac = 1;            for (int i = 1; i <= n; i++)            {                fac *= i;            }            //儲存結果            result[n] = fac;        }        static void Main(string[] args)        {            //向線程池中排入9個背景工作執行緒            for (int i = 1; i <= 9; i++)            {                //QueueUserWorkItem()方法:將工作任務排入線程池。                ThreadPool.QueueUserWorkItem(new WaitCallback(Fun), i);                // Fun 表示要執行的方法(與WaitCallback委託的聲明必須一致)。                // i   為傳遞給Fun方法的參數(obj將接受)。            }            //輸出計算結果            for (int i = 1; i <= 9; i++)            {                Console.WriteLine("線程{0}: {0}! = {1}", i, result[i]);            }        }    }}

 

C#多線程 線程池

聯繫我們

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