private void AddThread(CustomThread t) { t.workhorse = new Thread(() => { while (true) { bool taskhandling = false; bool casehandled = false; lock (t) { if (t.taskToExecute.taskstatus == TaskStatus.starting && t.state == ThreadState.waiting) { taskhandling = true; casehandled = true; } else { taskhandling = false; casehandled = false; } if (taskhandling) { try { t.state = ThreadState.working; t.taskToExecute.task.Invoke(); taskhandling = false; } catch (Exception ex) { t.state = ThreadState.completed; } t.taskToExecute.taskstatus = TaskStatus.done; } if (t.taskToExecute.callback != null && t.taskToExecute.taskstatus == TaskStatus.done && casehandled) { t.state = ThreadState.completed; t.taskToExecute.callback(); casehandled = false; } } } }); t.workhorse.Start(); ThreadQueue.Enqueue(t); }
/// <summary> /// /// </summary> public void RunTask() { Thread sceduler = new Thread(() => { while (true) { CustomTask t; TaskQueue.TryPeek(out t); if (t == null) { continue; } bool taskadded = false; int count = TaskQueue.Count; for (int i = 0; i < count; i++) { foreach (CustomThread thread in ThreadQueue) { lock (thread) { if (thread.state == ThreadState.completed) { Console.WriteLine("Free Thread :" + thread.id + " *** threads :" + ThreadQueue.Count.ToString()); CustomTask customtask; TaskQueue.TryDequeue(out customtask); if (customtask == null) { break; } thread.state = ThreadState.waiting; lock (customtask) { thread.taskToExecute = customtask; taskadded = true; } break; } } } if (!taskadded && ThreadQueue.Count < _maxThread) { CustomThread thread2 = new CustomThread(); lock (thread2) { thread2.id = Guid.NewGuid(); thread2.state = ThreadState.waiting; CustomTask customtask2; TaskQueue.TryDequeue(out customtask2); if (customtask2 == null) { break; } thread2.taskToExecute = customtask2; AddThread(thread2); taskadded = true; } } else if (!taskadded) { continue; } } } }); sceduler.Start(); }