void SleepWakeup(ResolverThread aThread, bool aSleep) { lock (this) { if (aSleep) { m_waitingThreads[aThread] = m_runningThreads[aThread]; m_runningThreads.Remove(aThread); } else { m_runningThreads[aThread] = m_waitingThreads[aThread]; m_waitingThreads.Remove(aThread); } } if (aSleep) { m_answerPoolThread.Interrupt(); SleepUntilInterrupt(); } else { ((Thread)m_runningThreads[aThread]).Interrupt(); } }
void AnswerPoolThread() { SleepUntilInterrupt(); for (;;) { if (m_answerQueue.Count == 0) { SleepUntilInterrupt(); continue; } object[] arrRequest = (object[])m_answerQueue.Peek(); if (m_waitingThreads.Count > 0) { IEnumerator en = m_waitingThreads.Keys.GetEnumerator(); en.MoveNext(); ResolverThread resThread = (ResolverThread)en.Current; resThread.m_request = (WebRequest)arrRequest[0]; resThread.m_client = (TcpClient)arrRequest[1]; resThread.m_stream = (NetworkStream)arrRequest[2]; Thread th = (Thread)m_waitingThreads[resThread]; WaitForSleep(th); SleepWakeup(resThread, false); m_answerQueue.Dequeue(); } else if (m_freeThreads + m_minThreads < m_maxThreads || m_maxThreads == -1) { ResolverThread resThread = new ResolverThread(this, true); resThread.m_request = (WebRequest)arrRequest[0]; resThread.m_client = (TcpClient)arrRequest[1]; resThread.m_stream = (NetworkStream)arrRequest[2]; Thread th = new Thread(new ThreadStart(resThread.Run)); StartStopFreeThread(resThread, th, true); th.Start(); m_answerQueue.Dequeue(); } else { SleepUntilInterrupt(); } } }
void SetUp() { for (int i = 0; i < m_minThreads; i++) { ResolverThread resThread = new ResolverThread(this, false); Thread th = new Thread(new ThreadStart(resThread.Run)); th.Start(); WaitForSleep(th); m_waitingThreads[resThread] = th; } m_answerPoolThread = new Thread(new ThreadStart(AnswerPoolThread)); m_answerPoolThread.Start(); WaitForSleep(m_answerPoolThread); }
void StartStopFreeThread(ResolverThread aResThread, Thread aThread, bool aStart) { lock (this) { if (aStart) { m_freeThreads++; m_runningFreeThreads[aResThread] = aThread; } else { m_freeThreads--; m_runningFreeThreads.Remove(aResThread); } m_answerPoolThread.Interrupt(); } }