实例介绍
【实例截图】
【核心代码】
using System; using System.Threading; using System.Timers; /* * An interesting discussion is on: http://www.dotnet247.com/247reference/msgs/5/25020.aspx * ThreadPool is designed to work with IO Completion Ports, it seems * * A slideshow on threads: http://research.microsoft.com/collaboration/university/europe/rotor/wshop-cambridge2threads.ppt * * Referenced rotor source: sscli\clr\src\vm\win32threadpool.cpp */ /* * 测试代码改编自Marc Clifton http://www.codeproject.com/KB/threads/threadtests.aspx */ namespace ThreadTests { using Amib.Threading;//for use SmartThreadPool class ThreadTest { static bool done = false; static decimal count2 = 0; static int threadDone = 0;//标志启用线程数? static System.Timers.Timer timer = new System.Timers.Timer(1000); static decimal[] threadPoolCounters = new decimal[10]; static Thread[] threads = new Thread[10]; static System.Timers.Timer[] threadTimers = new System.Timers.Timer[10]; static void Main(string[] args) { timer.Stop(); /*当 AutoReset 设置为 false 时,Timer 只在第一个 Interval 过后引发一次 Elapsed 事件。 若要保持以 Interval 时间间隔引发 Elapsed 事件,请将 AutoReset 设置为 true。*/ timer.AutoReset = false; timer.Elapsed = new ElapsedEventHandler(OnTimerEvent);//当timer.Start()时,触发事件 decimal total = 0; // raw test decimal count1 = SingleThreadTest();//单一线程,一跑到底 Console.WriteLine("Single thread count = " count1.ToString()); // create one thread, increment counter, destroy thread, repeat Console.WriteLine(); CreateAndDestroyTest();//创建一个线程,运算,然后销毁该线程 重复前面的动作 Console.WriteLine("Create and destroy per count = " count2.ToString()); // Create 10 threads and run them simultaneously //一次性创建10个线程,然后遍历使线程执行运算 Console.WriteLine(); InitThreadPoolCounters(); InitThreads(); StartThreads(); while (threadDone != 10) { }; Console.WriteLine("10 simultaneous threads:"); for (int i = 0; i < 10; i ) { Console.WriteLine("T" i.ToString() " = " threadPoolCounters[i].ToString() " "); total = threadPoolCounters[i]; } Console.WriteLine("Total = " total.ToString()); Console.WriteLine(); Console.WriteLine("///////////////////////////////////////////////////"); // using ThreadPool //直接通过线程池的QueueUserWorkItem方法,按队列执行10个任务 Console.WriteLine(); Console.WriteLine("ThreadPool:"); InitThreadPoolCounters(); QueueThreadPoolThreads(); while (threadDone != 10) { }; Console.WriteLine("ThreadPool: 10 simultaneous threads:"); total = 0; for (int i = 0; i < 10; i ) { // threadTimers[i].Stop(); // threadTimers[i].Dispose(); Console.WriteLine("T" i.ToString() " = " threadPoolCounters[i].ToString() " "); total = threadPoolCounters[i]; } Console.WriteLine("Total = " total.ToString()); // using SmartThreadPool //通过Amir Bar的SmartThreadPool线程池,利用QueueUserWorkItem方法,按队列执行10个任务 Console.WriteLine(); Console.WriteLine("SmartThreadPool:"); InitThreadPoolCounters(); QueueSmartThreadPoolThreads(); while (threadDone != 10) { }; Console.WriteLine("SmartThreadPool: 10 simultaneous threads:"); total = 0; for (int i = 0; i < 10; i ) { Console.WriteLine("T" i.ToString() " = " threadPoolCounters[i].ToString() " "); total = threadPoolCounters[i]; } Console.WriteLine("Total = " total.ToString()); // using ManagedThreadPool //通过Stephen Toub改进后的线程池,利用QueueUserWorkItem方法,按队列执行10个任务 Console.WriteLine(); Console.WriteLine("ManagedThreadPool:"); InitThreadPoolCounters(); QueueManagedThreadPoolThreads(); while (threadDone != 10) { }; Console.WriteLine("ManagedThreadPool: 10 simultaneous threads:"); total = 0; for (int i = 0; i < 10; i ) { Console.WriteLine("T" i.ToString() " = " threadPoolCounters[i].ToString() " "); total = threadPoolCounters[i]; } Console.WriteLine("Total = " total.ToString()); // using C#4.0 Parallel //通过Tasks.Parallel.For进行并行运算 Console.WriteLine(); Console.WriteLine("Parallel:"); InitThreadPoolCounters(); UseParallelTasks(); while (threadDone != 10) { }; Console.WriteLine("Parallel: 10 simultaneous threads:"); total = 0; for (int i = 0; i < 10; i ) { Console.WriteLine("T" i.ToString() " = " threadPoolCounters[i].ToString() " "); total = threadPoolCounters[i]; } Console.WriteLine("Total = " total.ToString()); } /// <summary> /// 单一线程,一跑到底 /// </summary> /// <returns></returns> static decimal SingleThreadTest() { done = false; decimal counter = 0; timer.Start(); while (!done) { counter; } return counter; } /// <summary> /// 创建一个线程,运算,然后销毁该线程 重复前面的动作 /// </summary> static void CreateAndDestroyTest() { done = false; timer.Start(); while (!done) { Thread counterThread = new Thread(new ThreadStart(Count1Thread)); counterThread.IsBackground = true;//后台线程 counterThread.Start(); while (counterThread.IsAlive) { }; } } static void Count1Thread() { count2; } static void Count2Thread() { int n = Convert.ToInt32(Thread.CurrentThread.Name);//取数组索引 while (!done) { threadPoolCounters[n]; } Interlocked.Increment(ref threadDone);//以原子操作的形式保证threadDone递增 } static void Count3Thread(object state) { int n = (int)state; while (!done) { threadPoolCounters[n]; } Interlocked.Increment(ref threadDone); } static object Count4Thread(object state) { int n = (int)state; while (!done) { threadPoolCounters[n]; } Interlocked.Increment(ref threadDone); return null; } static void Count5Thread(object state) { int n = (int)state; while (!done) { threadPoolCounters[n]; } Interlocked.Increment(ref threadDone); } static void Count6Thread(object state) { int n = (int)state; while (!done) { threadPoolCounters[n]; } Interlocked.Increment(ref threadDone); } /*BEGIN * TimerThread0~TimerThread9是没有使用的测试方法,作者写此10个方法的时候可能没有考虑好合适的传参方法 */ //static void TimerThread0(object src, ElapsedEventArgs e) //{ // threadPoolCounters[0]; //} //static void TimerThread1(object src, ElapsedEventArgs e) //{ // threadPoolCounters[1]; //} //static void TimerThread2(object src, ElapsedEventArgs e) //{ // threadPoolCounters[2]; //} //static void TimerThread3(object src, ElapsedEventArgs e) //{ // threadPoolCounters[3]; //} //static void TimerThread4(object src, ElapsedEventArgs e) //{ // threadPoolCounters[4]; //} //static void TimerThread5(object src, ElapsedEventArgs e) //{ // threadPoolCounters[5]; //} //static void TimerThread6(object src, ElapsedEventArgs e) //{ // threadPoolCounters[6]; //} //static void TimerThread7(object src, ElapsedEventArgs e) //{ // threadPoolCounters[7]; //} //static void TimerThread8(object src, ElapsedEventArgs e) //{ // threadPoolCounters[8]; //} //static void TimerThread9(object src, ElapsedEventArgs e) //{ // threadPoolCounters[9]; //} /*END*/ /// <summary> /// 将数组和线程数标志threadDone回到初始状态 /// </summary> static void InitThreadPoolCounters() { threadDone = 0; for (int i = 0; i < 10; i ) { threadPoolCounters[i] = 0; } } /// <summary> /// 初始化10个线程 /// </summary> static void InitThreads() { for (int i = 0; i < 10; i ) { threads[i] = new Thread(new ThreadStart(Count2Thread)); threads[i].IsBackground = true; threads[i].Name = i.ToString();//将当前线程的Name赋值为数组索引,在Count2Thread方法中获取对应数组 } } /// <summary> /// 开始多线程运算 /// </summary> static void StartThreads() { done = false; timer.Start(); for (int i = 0; i < 10; i ) { threads[i].Start(); } } /// <summary> /// ThreadPool测试 /// </summary> static void QueueThreadPoolThreads() { done = false; for (int i = 0; i < 10; i ) { // System.Timers.Timer t=new System.Timers.Timer(1); // threadTimers[i]=t; // t.AutoReset=true; //ThreadPool.QueueUserWorkItem(new WaitCallback(Count3Thread), i); WaitCallback wcb = new WaitCallback(Count3Thread); int workerThreads, availabeThreads; ThreadPool.GetAvailableThreads(out workerThreads, out availabeThreads); if (workerThreads > 0)//可用线程数>0 { ThreadPool.QueueUserWorkItem(wcb, i); } else { //to do 可以采取一种策略,让这个任务合理地分配给线程 } } /* threadTimers[0].Elapsed =new ElapsedEventHandler(TimerThread0); threadTimers[1].Elapsed =new ElapsedEventHandler(TimerThread1); threadTimers[2].Elapsed =new ElapsedEventHandler(TimerThread2); threadTimers[3].Elapsed =new ElapsedEventHandler(TimerThread3); threadTimers[4].Elapsed =new ElapsedEventHandler(TimerThread4); threadTimers[5].Elapsed =new ElapsedEventHandler(TimerThread5); threadTimers[6].Elapsed =new ElapsedEventHandler(TimerThread6); threadTimers[7].Elapsed =new ElapsedEventHandler(TimerThread7); threadTimers[8].Elapsed =new ElapsedEventHandler(TimerThread8); threadTimers[9].Elapsed =new ElapsedEventHandler(TimerThread9); for (int i=0; i<10; i ) { threadTimers[i].Start(); } */ timer.Start(); } /// <summary> /// SmartThreadPool测试 /// </summary> static void QueueSmartThreadPoolThreads() { SmartThreadPool smartThreadPool = new SmartThreadPool(); // Create a work items group that processes // one work item at a time IWorkItemsGroup wig = smartThreadPool.CreateWorkItemsGroup(1); done = false; timer.Start(); for (int i = 0; i < 10; i ) { wig.QueueWorkItem(new WorkItemCallback(Count4Thread), i); } // Wait for the completion of all work items in the work items group wig.WaitForIdle(); smartThreadPool.Shutdown(); } /// <summary> /// ManagedThreadPool测试 /// </summary> static void QueueManagedThreadPoolThreads() { done = false; timer.Start(); for (int i = 0; i < 10; i ) { Toub.Threading.ManagedThreadPool.QueueUserWorkItem(new WaitCallback(Count5Thread), i); } } /// <summary> /// 并行运算测试 /// </summary> static void UseParallelTasks() { done = false; timer.Start(); // System.Threading.Tasks.Parallel.For - for 循环的并行运算 System.Threading.Tasks.Parallel.For(0, 10, (i) => { Count6Thread(i); }); } static void OnTimerEvent(object src, ElapsedEventArgs e) { done = true; } } }
标签: thread threadpool
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论