程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 實現單線程線程池並調用實例

C# 實現單線程線程池並調用實例

編輯:C#入門知識

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ConsoleCsharp
{
    class Proxy
    {
        System.Threading.Thread worker;
        Queue<WaitCallback> queue;
       // List<WaitCallback> list;
        System.Threading.Semaphore sm = new Semaphore(1, 1);
        public Proxy()
        {
            queue = new Queue<WaitCallback>();
            worker = new System.Threading.Thread(this.run);
            worker.Name = "worker";
            worker.Start();
        }
        public void run()
        {
            for (; ; )
            {
                WaitCallback wc = null;
                sm.WaitOne();
                if (queue.Count >= 1)
                {
                    wc = queue.Dequeue();
                }
                sm.Release();
                if (wc != null)
                {
                    wc.Invoke(null);
                }
            }
        }

        public void handle(WaitCallback wc)
        {
            sm.WaitOne();
            queue.Enqueue(wc);
            sm.Release();
        }
    }
    class Caller
    {
        Proxy pro;
        public Caller()
        {
            pro = new Proxy();
        }
        public void doFunc(int i)
        {
            pro.handle(delegate {
                System.Console.Out.WriteLine(Thread.CurrentThread.Name+":" + i);
            });
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Caller c = new Caller();
            for (int i = 0; i < 100; ++i)
            {
                c.doFunc(i);
            }
            while(true)
            Thread.Sleep(100);
        }
    }
}


作者:jingshishengxu

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved