Task queue : Queue « Collections Data Structure « C# / C Sharp






Task queue

        

using System.Collections.Generic;
using System.Threading;

namespace PS.WSSDeploy.VSAddin.Utils
{
    public interface Task
    {
        void TaskExecute();
    }

    public class TaskQueue
    {
        private readonly Queue<Task> queue = new Queue<Task>();
        public void Enqueue(Task task)
        {
            lock (queue)
            {
                queue.Enqueue(task);
                if (queue.Count == 1) RunTaskInThreadPool();
            }
        }
        public void Clear()
        {
            lock (queue)
            {
                queue.Clear();
            }
        }
        private void RunTaskInThreadPool()
        {
            ThreadPool.QueueUserWorkItem(Execute);
        }
        private void Execute(object state)
        {
            Task task = null;
            lock (queue)
            {
                if (queue.Count > 0)
                    task = queue.Peek();
            }

            if (task != null)
            {
                task.TaskExecute();
            }
            lock (queue)
            {
                if (queue.Count > 0)
                {
                    queue.Dequeue();
                }
                if (queue.Count > 0)
                {
                    RunTaskInThreadPool();
                }
            }
        }
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Put elements into a queue
2.Put user-defined objects to Queue collection
3.Implements the queue data type using an arrayImplements the queue data type using an array
4.A queue class for charactersA queue class for characters
5.illustrates the use of a Queueillustrates the use of a Queue
6.Queue testQueue test
7.Add exception handling to the queue classesAdd exception handling to the queue classes
8.Demonstrate the Queue classDemonstrate the Queue class
9.Priority Queue
10.Queue(T) Class represents a first-in, first-out collection of objects.
11.Priority Queue (2)
12.Dequeue
13.Implements a non-locking queue
14.Cyclic Queue
15.Syncronized Queue