Single Thread task queue

Source: Internet
Author: User
Tags add time

<span style= "Font-weight:bold;" > The code below solves the problem of avoiding creating new threads to circumvent the thread pool's creation of multithreaded solutions to waste resources </span>
Using system;using system.collections.generic;using system.text;using system.threading;namespace MyThreadPool{// <summary>////Thread task queue///</summary>//<typeparam name= "T" ></typeparam> public class Backgr oundtasks<t> {//<summary>///function with parameter without return value///</summary> private action& Lt       T> Function;       <summary>///FIFO queue///</summary> private queue<t> list = new queue<t> ();       <summary>///constructors///</summary>//<param name= "Fun" ></param> Public Backgroundtasks (action<t> fun) {this.           Function = fun;           Thread th = new Thread (Run); Th.           IsBackground = true; Th.       Start (); }///<summary>///Execute Thread Method queue///</summary> private void Run () {Whil E (True) {if (list.              Count = = 0) {Thread.Sleep (10);                   } else {T data; Lock (list) {data = list.                   Dequeue ();                   } try {Function (data);               } catch {} thread.sleep (10); }}}///<summary>//Add queue to thread///</summary>//<param name= "da Ta "></param> public void Add (T data) {Lock (list) {list.           Enqueue (data); }       }    }}
Using system;using system.collections.generic;using system.text;using system.threading;namespace MyThreadPool{     class program    {        static void Main (string[] args)         {            Backgroundtasks.add ((obj) = {          &NBS P     Console.WriteLine ("Add time for this task is 1:{0}", obj. ToString ());           },datetime.now.millisecond);          &NBS P  Backgroundtasks.add ((obj) =>            {                Console.WriteLine ("Add time for this task is 2:{0}", obj. ToString ());           }, DateTime.Now.Millisecond);          &NBS P  Backgroundtasks.add ((obj) =>            {                Console.WriteLine ("Add time for this task is 3:{0}", Obj. ToString ());           }, DateTime.Now.Millisecond);          &NBS P  Backgroundtasks.add ((obj) =>            {                Console.WriteLine ("Add time for this task is 4:{0}", obj. ToString ());           }, DateTime.Now.Millisecond);          &NBS P Custom thread queue incoming generic parameter, create only one thread             backgroundtasks<datetime> task = new Backgroundt Asks<datetime> (obj =>            {             )   Console.WriteLine ("Add time for this task is 5:{0}", obj. ToString ());           });            task.  ADD (DateTime.Now);           //thread pool method each call creates a new thread             Threadpool.setmaxthreads (; )     &nbsp     ThreadPool.QueueUserWorkItem ((obj) = {                CONSOLE.WR Iteline ("Add time for this task is 6:{0}", obj. ToString ());           }, DateTime.Now);            CONSOLE.R EAD ();       }   }   //<summary>   ///thread task queue    / </summary>    public class backgroundtasks    {       //<summary&gt ;       //Task entity        //</summary>        Private C Lass taskentity        {            public action<object> Function ;            public object data;            public taskentity ( action<object> func, Object data)             {                this. Function = func;                this. Data = data;           }       }       //&LT;SU  mmary>       //FIFO queue        //</summary>        static queue<taskentity> list = new queue<taskentity> ();       //&LT;SUMMARY&GT;&NBSP ;      //constructor creation thread        //</summary>        static backg Roundtasks ()          {            thread thread = new Thread (Run); nbsp           thread. IsBackground = true;            thread. Start ();       }       //<summary>       ///Executive line Cheng Legal queue        //</summary>        static void Run ()         {          & nbsp while (true)             {                if (list. Count = 0)                 {              &NBSP ;     Thread.Sleep (; )              }        &NBS P       else                {          &NBSP ;         taskentity entity;                    Lock ( List)                     {            &NBS P           entity = list. Dequeue ();                   }&NBsp                   try                    {                        entity. Function (entity. Data);                   }            &NB Sp       Catch {}                    Thread.Sleep (Ten);                 }           }      & nbsp }       //<summary>       //Add Task Queue        //< /summary>       //<param name= "func" ></param>       //&LT;PA Ram name= "Data" ></param>        public static void Add (action<object> func, Object dat A)   &NBsp     {            Lock (list)             {  &nbs P             list. Enqueue (New Taskentity (func, data));           }       }         }}
because the tasks in the queue are single-threaded, some tasks may result in a long time before they are executed, or restarting IIS causes many tasks to be discarded without being executed. However, this design is suitable for many "general situations".

Single Thread task queue

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.