/// <summary> /// Starts the tasks execution. /// </summary> /// <returns>If has reach the timeout false, otherwise true.</returns> public override bool Start() { base.Start(); m_threadPool = new SmartThreadPool(); try { m_threadPool.MinThreads = MinThreads; m_threadPool.MaxThreads = MaxThreads; var workItemResults = new IWorkItemResult[Tasks.Count]; for (int i = 0; i < Tasks.Count; i++) { var t = Tasks[i]; workItemResults[i] = m_threadPool.QueueWorkItem(new WorkItemCallback(Run), t); } m_threadPool.Start(); // Timeout was reach? if (!m_threadPool.WaitForIdle(Timeout.TotalMilliseconds > int.MaxValue ? int.MaxValue : Convert.ToInt32(Timeout.TotalMilliseconds))) { if (m_threadPool.IsShuttingdown) { return true; } else { m_threadPool.Cancel(true); return false; } } foreach (var wi in workItemResults) { Exception ex; wi.GetResult(out ex); if (ex != null) { throw ex; } } return true; } finally { m_threadPool.Shutdown(true, 1000); m_threadPool.Dispose(); IsRunning = false; } }
public void CancelSTPWorkItems() { // I don't use lock on the counter, since any number above 0 is a failure. // In the worst case counter will be equal to 1 which is still not 0. int counter = 0; SmartThreadPool stp = new SmartThreadPool(); for (int i = 0; i < 10; i++) { stp.QueueWorkItem( state => { Thread.Sleep(500); ++counter; return null; } ); } Thread.Sleep(100); stp.Cancel(true); Assert.AreEqual(counter, 0); stp.Shutdown(); }