C # multithreading -- thread pool and callback function

Source: Internet
Author: User

You may have encountered: When a thread does things and other threads wait, it may be a waste of time because the thread that does not do things is waiting.

We can solve this problem through threadpool in the thread pool. We can use threadpool. queueuserworkitem (callback function, object) to encapsulate parameters in a Class Object and pass them to the callback function for execution.

Theadpool usage:

1. Create a manualresetevent object, which is like a signal lamp, indicating the suspension and execution of the thread;

2. When creating a manualresetevent object, you can specify the default state: True indicates that there is a signal, and false indicates that there is no signal;

3. Call the reset () method to reset the status;

4. Call the waitone () method to keep the thread in the waiting state;

5. Call the Set () method to set the status.

using System;using System.Collections.Generic;using System.Text;using System.Threading;using System.Collections;namespace Demo{    public class ParamObject    {        public int number;        public ParamObject (int number)        {            this.number = number;        }    }    public class ThreadClass    {        public Hashtable aHashTable;        public ManualResetEvent aManualResetEvent;        public static int iCount = 0;        public static int iMaxCount = 0;        public ThreadClass(int maxCount)        {            aHashTable = new Hashtable(maxCount);            iMaxCount = maxCount;        }        public void ThreadRun(object aParamObject)        {            Console.WriteLine("HashCode: {0}, Number in Object: {1}", Thread.CurrentThread.GetHashCode(), ((ParamObject)aParamObject).number);            lock (aHashTable)            {                if (!aHashTable.ContainsKey(Thread.CurrentThread.GetHashCode()))                {                    aHashTable.Add(Thread.CurrentThread.GetHashCode(), 0);                }                aHashTable[Thread.CurrentThread.GetHashCode()] = (int)aHashTable[Thread.CurrentThread.GetHashCode()] + 1;            }            Thread.Sleep(3000);                        Interlocked.Increment(ref iCount);            if (iCount == iMaxCount)            {                Console.WriteLine("Setting aManualResetEvent...");                aManualResetEvent.Set();            }        }    }    class Program    {       public static void Main(string[] args)       {           bool enableThreadPool = false;           int iMaxCount = 20;           ManualResetEvent aManualResetEvent = new ManualResetEvent(false);           Console.WriteLine("Insert {0} items to Thread Pool.", iMaxCount);           ThreadClass aThreadClass = new ThreadClass(iMaxCount);           aThreadClass.aManualResetEvent = aManualResetEvent;           // First, add an item to check if your system supports ThreadPool API function or not.           try           {               ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(0));               enableThreadPool = true;           }           catch (NotSupportedException ex)           {               Console.WriteLine("Thread Pool API is not supported in this system.");               enableThreadPool = false;           }           if (enableThreadPool)           {               for (int i = 1; i < iMaxCount; i++)               {                   ThreadPool.QueueUserWorkItem(new WaitCallback(aThreadClass.ThreadRun), new ParamObject(i));               }               Console.WriteLine("Waiting for thread pool to drain");               aManualResetEvent.WaitOne(Timeout.Infinite, true);               Console.WriteLine("Thread Pool has been drained.");               Console.WriteLine("Load threads info:");               foreach (object key in aThreadClass.aHashTable.Keys)               {                   Console.WriteLine("Key: {0}, Value: {1}", key, aThreadClass.aHashTable[key]);               }           }           Console.ReadLine();       }    }}

 

 

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.