⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 workqueue.cs

📁 c#实现的工作队列
💻 CS
字号:
using System;


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


namespace WorkQueue
{
	class WorkQueue
	{
        
		private int nThreads; 						//工作线程数
		private static Thread[] threads;			//队列线程数组
    	
		protected static Queue  queue;				//队列
            
		//构造函数
		public WorkQueue(int nThreads) 
		{            
			this.nThreads = nThreads;

			queue = new Queue();
           
			threads = new Thread[nThreads];

			for (int i = 0; i < nThreads; i++) 
			{
				threads[i] = new Thread(new ThreadStart(WaitAndWork));
				threads[i].Start();
				//Thread.Sleep(1000);
			}
			//Thread.Sleep(1000);
		}

		public void execute(Thread  r) 
		{
			lock (queue)
			{
				queue.Enqueue(r);
				for(int i=0;i<nThreads;i++)
				{
					if(threads[i].ThreadState == ThreadState.Suspended)
					{
						threads[i].Resume();
						break;
					}

				}
			}
		}

		private void WaitAndWork()
		{
			Thread r;
            
			while (true) 
			{
				lock (queue)
				{
					while (queue.Count == 0) 
					{
						try 
						{
							Thread.CurrentThread.Suspend();
								
						}
						catch (Exception ignored) 
						{

						}
					}
					r = (Thread)queue.Dequeue();

				}

				// If we don′t catch RuntimeException,
				// the pool could leak threads
				try 
				{
					r.Start();
				} 
				catch (Exception e) 
				{
					// You might want to log something here
				}
			}

		}

	}
	

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -