C # Performs a fixed number of tasks self-control the number of threads entering the thread pool, multitasking but concurrent data qualification

Source: Internet
Author: User


Source of thought: http://bbs.csdn.NET/topics/390819824, quoting the method provided by a netizen on this page.


Title: I now have 100 tasks that require multiple threads to complete, but limit the concurrent number to 5.

Principle: Initially enable 5 threads, then let the process in the thread complete, and then go to fetch the next task, start the next thread.

[CSharp]View PlainCopyPrint?
  1. Public class mytasklist
  2. {
  3. Public list<action> Tasks = New  list<action> ();
  4. Public void Start ()
  5. {
  6. for (var i = 0; i < 5; i++)
  7. Startasync ();
  8. }
  9. Public   Event Action completed;
  10. Public void startasync ()
  11. {
  12. Lock (Tasks)
  13. {
  14. if (Tasks.count > 0)
  15. {
  16. var t = tasks[tasks.count-1];
  17. Tasks.remove (t);
  18. ThreadPool.QueueUserWorkItem (h =
  19. {
  20. T ();
  21. Startasync ();
  22. });
  23. }
  24. Else if (completed! = null)
  25. Completed ();
  26. }
  27. }
  28. }
    public class Mytasklist    {public        list<action> Tasks = new list<action> ();         public void Start ()        {for            (var i = 0; i < 5; i++)                Startasync ();        }         public event Action completed;         public void Startasync ()        {            lock (Tasks)            {                if (Tasks.count > 0)                {                    var t = tasks[ TASKS.COUNT-1];                    Tasks.remove (t);                    ThreadPool.QueueUserWorkItem (h =                    {                        t ();                        Startasync ();                    });                }                else if (completed! = NULL)                    completed ();}}}    
Call Mode:

1, automatically join the 100 test tasks, each run time is uncertain, random.

2, here the Startasync method is instantly over, does not block at all, does not wait for what while loop ends

[CSharp]View PlainCopyPrint?
  1. var rnd = New  Random ();
  2. var lst = new mytasklist ();
  3. for (var i = 0; i <; i++)
  4. {
  5. var s = rnd. Next (10);
  6. var j = i;
  7. var test task = new Action (() =
  8. {
  9. Console.WriteLine (string.  Format ("{0} tasks (spents {1} seconds) has begun", J, s));
  10. Thread.Sleep (S * 1000);
  11. Console.WriteLine (string.  Format ("{0} tasks (spents {1} seconds) has ended", J, s));
  12. });
  13. Lst. Tasks.add (test Task);
  14. }
  15. lst.completed + = () = Console.WriteLine ("____________________ no more missions anymore!"  ");
  16. Lst. Start ();
            var rnd = new Random ();            var lst = new Mytasklist ();            for (var i = 0; i < i++)            {                var s = rnd. Next (ten);                var j = i;                var test task = new Action (() =                {                    Console.WriteLine (string. Format ("{0} tasks (spents {1} seconds) has begun", J, s));                    Thread.Sleep (S * +);                    Console.WriteLine (String. Format ("{0} tasks (spents {1} seconds) has ended", J, s);                });                Lst. Tasks.add (test Task);            }            lst.completed + = () = Console.WriteLine ("____________________ no more missions anymore!" ");            Lst. Start ();


You use the custom maximum number of threads in your program, and then loop through the threads that enable the maximum number of threads to perform the task, wait for the thread to finish, exit this run method and thread before you call the Enable thread method call the next thread, loop until it is complete :

[CSharp]View PlainCopyPrint?
  1. autoresetevent[] waitenents = New  Autoresetevent[n_max_thread];
  2. for (int i = 0; i < n_max_thread; i++)
  3. {
  4. Calcstate.wait_event = waitenents[i] = new AutoResetEvent (false);
  5. Startasync (CalcState);
  6. }
  7. Autoresetevent.waitall (waitenents);
  8. Private static void startasync (calcstate calcstate)
  9. {
  10. Lock (Calcstate.locker_listformula)
  11. {
  12. if (CalcState.lstFormula.Count > 0)
  13. {
  14. Calcstate.formulaattr = CalcState.lstFormula.ElementAt (calcstate.lstformula.count-1). Value;
  15. CalcState.lstFormula.Remove (CalcState.lstFormula.ElementAt (calcstate.lstformula.count-1). Key);
  16. ThreadPool.QueueUserWorkItem (new WaitCallback (execasync), calcstate);
  17. }
  18. Else   
  19. {
  20. Calcstate.wait_event. Set ();
  21. }
  22. }
  23. }
  24. Private static void Execasync (object obj)
  25. {
  26. CalcState calcstate = obj as calcstate;
  27. Startcalcformula (CalcState);
  28. //recursive processing of the next formula   
  29. Startasync (CalcState);
  30. }
  31. Private static void Startcalcformula (calcstate calcstate)
  32. {
  33. }
        autoresetevent[] waitenents = new Autoresetevent[n_max_thread]; for (int i = 0; i < N_max_thread; i++) {calcstate.wait_event = waitenents[i] = new AutoResetEvent (f             Alse);        Startasync (CalcState);        } autoresetevent.waitall (waitenents);                private static void Startasync (CalcState calcstate) {lock (Calcstate.locker_listformula) { if (CalcState.lstFormula.Count > 0) {calcstate.formulaattr = CalcState . Lstformula.elementat (Calcstate.lstformula.count-1).                    Value; CalcState.lstFormula.Remove (CalcState.lstFormula.ElementAt (calcstate.lstformula.count-1).                    Key);                ThreadPool.QueueUserWorkItem (New WaitCallback (Execasync), calcstate); } else {calcstate.wait_event.                Set (); }}} private static void Execasync (Object obj)        {CalcState calcstate = obj as calcstate;            Startcalcformula (CalcState);        Recursive processing of the next formula Startasync (CalcState); } private static void Startcalcformula (CalcState calcstate) {}


C # Performs a fixed number of tasks self-control the number of threads entering the thread pool, multitasking but concurrent data qualification

Related Article

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.