C#多线程 线程池

时间:2023-03-10 02:57:33
C#多线程 线程池

实例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();
        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
    {
        // 用于保存每个线程的计算结果
        ];

        //注意:由于WaitCallback委托的声明带有参数,
        //所以将被调用的Fun方法必须带有参数,即:Fun(object obj)。
        static void Fun(object obj)
        {
            int n = (int)obj;

            //计算阶乘
            ;
            ; i <= n; i++)
            {
                fac *= i;
            }

            //保存结果
            result[n] = fac;
        }

        static void Main(string[] args)
        {
            //向线程池中排入9个工作线程
            ; i <= ; i++)
            {
                //QueueUserWorkItem()方法:将工作任务排入线程池。
                ThreadPool.QueueUserWorkItem(new WaitCallback(Fun), i);
                // Fun 表示要执行的方法(与WaitCallback委托的声明必须一致)。
                // i   为传递给Fun方法的参数(obj将接受)。
            }

            //输出计算结果
            ; i <= ; i++)
            {
                Console.WriteLine("线程{0}: {0}! = {1}", i, result[i]);
            }
        }

    }
}