/// <summary> /// Add task to running cache. /// </summary> /// <param name="task"></param> /// <param name="attachThread"></param> private void AddRunning(IPoolTask task, Task attachThread) { runningLocker.EnterWriteLock(); task.AttachThread(attachThread); running.Add(task.Key, task); runningLocker.ExitWriteLock(); }
/// <summary> /// Create a thread, and fetch a task to run in it. /// </summary> /// <returns></returns> private bool AddThread() { if (toState != TaskPoolState.RUN) { return(false); } IPoolTask task = taskFetch.FetchNewTask(); if (task == null) { return(false); } Task thread = null; thread = new Task(() => { while (true) { task.Run(); /// When current task is finished, remove it from <see cref="running"/>. locker.EnterWriteLock(); running.Remove(task.Key); locker.ExitWriteLock(); /// If pool will run, then fetch a new task and add it to <see cref="running"/> if (toState == TaskPoolState.RUN) { task = taskFetch.FetchNewTask(); if (task != null) { locker.EnterWriteLock(); task.AttachThread(thread); running.Add(task.Key, task); locker.ExitWriteLock(); } } else { task = null; } /// When this thread are running to end, get count of running tasks. /// If count equals 0, it means there is no running task. /// Then set current state to <see cref="TaskPoolState.PAUSE"/> if (task == null) { int count = 0; locker.EnterUpgradeableReadLock(); count = running.Count; if (count == 0) { locker.EnterWriteLock(); currentState = TaskPoolState.PAUSE; locker.ExitWriteLock(); } locker.ExitUpgradeableReadLock(); break; } } }); task.AttachThread(thread); locker.EnterWriteLock(); running.Add(task.Key, task); locker.ExitWriteLock(); thread.Start(); return(true); }