码迷,mamicode.com
首页 > 编程语言 > 详细

C#多线程 线程池

时间:2015-04-16 09:01:08      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:

实例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#多线程 线程池

标签:

原文地址:http://www.cnblogs.com/Sky-cloudless/p/4430992.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!