Beispiel #1
0
        /// <summary>
        /// Add request to task Queue, that way it can be run (with delegate to run after!).
        /// </summary>
        /// <param name="method"> Method you want to call, format in lambda AKA like: () => {method in question} </param>
        /// <param name="callback">What to call after the call has been completed</param>
        /// <returns>Returns A task that will contain the value returned, a task can also in theory be re-added in the future</returns>
        public ThreadTaskRequest AddRequest(Func <object> method, Action <CallbackArgs <object> > callback = null)
        {
            if (method == null)
            {
                throw new ArgumentNullException(nameof(method));
            }

            ThreadTaskRequest taskClass        = new ThreadTaskRequest(method, callback);
            PooledThreadClass lowestTaskThread = null;
            int lowestTaskNumber = int.MaxValue;

            foreach (PooledThreadClass threadClass in _pooledThreadClasses)
            {
                if (lowestTaskNumber > threadClass.TasksAssigned.Count)
                {
                    lowestTaskNumber = threadClass.TasksAssigned.Count;
                    lowestTaskThread = threadClass;
                }
            }


            if (lowestTaskThread?.TaskAccessLock != null)
            {
                lock (lowestTaskThread?.TaskAccessLock)
                {
                    lowestTaskThread?.TasksAssigned.Add(taskClass);
                }
            }
            return(taskClass);
        }
        //Finds a task and uses it unless there are no more tasks then just returns
        /// <summary>
        /// Loop the thread takes
        /// </summary>
        ///
        void ThreadLoop()
        {
            while (!PendingShutdown)
            {
                ThreadTaskRequest currentTask = null;
                lock (TaskAccessLock)
                {
                    if (TasksAssigned.Count > 0 && !BIsPaused)
                    {
                        if (BIsIdle)
                        {
                            BIsIdle = false;
                        }

                        currentTask = TasksAssigned[0];
                        TasksAssigned.RemoveAt(0);
                    }
                    else
                    {
                        if (!BIsIdle)
                        {
                            BIsIdle = true;
                        }
                    }
                }

                if (currentTask != null)
                {
                    currentTask.Result = currentTask.Method();
                    if (currentTask.Callback != null)
                    {
                        currentTask.CallbackArgs.SetThreadResult(currentTask.Result);
                        currentTask.Callback(currentTask.CallbackArgs);
                    }

                    currentTask.BHasRun = true;
                }
            }
        }