Demo:this
class Program { static void Main(string[] args) { Action<string> work = (string p) => { var id= Thread.CurrentThread.ManagedThreadId; Console.WriteLine(id+"線程正在執行:"+p); }; ThreadTask<string> t = new ThreadTask<string>(1000, work); t.Run(); t.AddTask("a"); t.AddTask("b"); for (int i = 0; i <= 1000; i++) { t.AddTask(i.ToString()); } Console.WriteLine(" main over"); Console.ReadLine(); } }
ThreadTask:spa
/// <summary> /// 並行多任務 /// </summary> /// <typeparam name="T"></typeparam> public class ThreadTask<T> { private readonly Queue<T> _tasks = null; private readonly int _threadCount = 1; private static object o = new object(); private readonly Action<T> _work = null; public ThreadTask(int threadCount, Action<T> work) { this._tasks = new Queue<T>(); this._threadCount = threadCount; this._work = work; } /// <summary> /// 運行 /// </summary> public void Run() { for (int i = 1; i <= _threadCount; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(WaitCallback), i); } } /// <summary> /// 增長任務到隊列 /// </summary> /// <param name="t"></param> public void AddTask(T t) { lock (o) { _tasks.Enqueue(t); } } void WaitCallback(object state) { while (true) { T t = default(T); lock (o) { if (_tasks.Count > 0) { t = _tasks.Dequeue(); } else { continue; } } _work(t); } } }