Use of the thread pool for automated control

Source: Internet
Author: User
Tags volatile

Yesterday's anti-compilation saw the thread pool implemented by the company's project chief architect. Surprisingly, in the absence of the. NET 4 availability era. The thought and the technique are quite good. Admire.

The thread pool here is a class I always thought it was a bit of a name. In fact, a class within the implementation of the FIFO queue, the temporary data into this queue, "Thread pool class" content in accordance with the queued order to trigger an event responsible for parsing the checksum, and to pass the data of this event.

Okay, on the code:

    <summary>////Custom thread pool class, does not rely on. NET queue to implement FIFO processing queue data///</summary> public class Corethreadpool : IDisposable {//<summary>////Queue element declaration///</summary> [StructLayout (Layoutkin            D.sequential)] Private class Pooldata {//<summary>//external required data placed in the queue            </summary> public Object Data; <summary>///commands to be executed (Exit/command (custom))///</summary> public Corethread            Pool.poolcommand Command;            Public Pooldata () {this.command = CoreThreadPool.PoolCommand.Exit; } public Pooldata (object data) {this.                data = data;            This.command = CoreThreadPool.PoolCommand.Command;            } public pooldata (Corethreadpool.poolcommand cmd) {this.command = cmd; }} Protected enum Poolcommand {Command, Exit} protected Safefilehandle Complateport        ;        <summary>///thread pool main thread///</summary> protected thread thread;        protected volatile bool isopened;        [Method:compilergenerated]        [compilergenerated] public event action<object> Exceute;        [Method:compilergenerated]        [compilergenerated] public event action<object> Exitexceute;            <summary>////thread pool is running////</summary> public bool isopened {get            {return this.isopened;            } set {this.isopened = value; }} [DllImport ("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern Sa Fefilehandle CreateIoCompletionPort (IntPtr filehandle, IntPtr existingcompletionport, IntPtr completionkey, uint NumberOfConcurrentThreads); [DllImport ("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool Getqueuedcomple Tionstatus (Safefilehandle Completionport, out uint lpnumberofbytestransferred, out IntPtr lpCompletionKey, out INTPTR        lpoverlapped, uint dwmilliseconds); [DllImport ("Kernel32", CharSet = CharSet.Auto)] private static extern bool PostQueuedCompletionStatus (Safefilehandl        e Completionport, uint dwnumberofbytestransferred, IntPtr dwcompletionkey, IntPtr lpoverlapped); <summary>///start thread pool main thread///</summary> public void Start () {IsOpen            ed = true; if (thread! = null) {throw new Exception ("The thread pool is already in the boot state!")            ");            } Complateport = CreateIoCompletionPort (new IntPtr ( -1), IntPtr.Zero, IntPtr.Zero, 0u); if (complateport.isinvalid) {throw new Exception (string. Format ("Error creating IOCP! The reason is: {0}", Marshal.GetLastWin32Error ().            ToString ())); The thread = new Thread (The new Parameterizedthreadstart (this).            Run)); Thread.        Start (Complateport); }///<summary>///External submit data object to queue///</summary>//<param name= "Data" ></p        aram> public void Post (object data) {PostData (new Corethreadpool.pooldata (data)); }///<summary>///thread pool main thread execution logic///</summary>//<param name= "Completionportid "></param> private void Run (object completionportid) {Safefilehandle Completionport = (                        Safefilehandle) Completionportid;                while (isopened) {uint num;                IntPtr IntPtr;                INTPTR value; Remove the front-most object from the queue Corethreadpool.getqueuedcompletionstatus (completionport, out num, out intPtr, out value, 429                4967295U); if (num > 0u) {GCHandle GCHandle = gchandle.fromintptr (value);                    Corethreadpool.pooldata Pooldata = (corethreadpool.pooldata) gchandle.target;                    Gchandle.free ();                        if (pooldata.command! = CoreThreadPool.PoolCommand.Command) {isopened = false;                    Break                } raiseexecute (Pooldata.data); }} raiseexitexecute ("The thread pool has stopped.            ");            isopened = false;        thread = NULL; }//<summary>//Trigger Execute Event///</summary>//<param name= "Data" ></p aram> private void Raiseexecute (object data) {Exceute?.        Invoke (data); }///<summary>//Trigger Exitexecute Events///</summary>//<param name= "Data" &GT;&L t;/param> private void Raiseexitexecute (obJect data) {Exitexceute?.        Invoke (data);            }///<summary>//End thread pool main thread///</summary> public void Stop () {            PostData (New Pooldata (Poolcommand.exit));        isopened = false; }///<summary>//internal submission of data to the thread pool queue///</summary>//<param name= "Data" ><                /param> private void PostData (Pooldata data) {if (complateport.isclosed) {            Return            } GCHandle value = GCHandle.Alloc (data);        PostQueuedCompletionStatus (Complateport, (UINT) intptr.size, IntPtr.Zero, gchandle.tointptr (value)); public void Dispose () {if (This.thread! = NULL && this.thread.ThreadState! = system.th Reading. threadstate.stopped) {this.            Stop (); }        }    }

Code highlights: Queues are implemented using the operating system, using the Windows API. Bull Bar.

Because the project is now dependent on. NET 4. So the imitation, after some testing, found that almost, but still think in the multi-threaded environment to use concurrentqueue will be better.

 <summary>////Custom thread pool class, using Concurrentqueue to implement FIFO processing queue data///</summary> public class Coolthreadpool        <T> {protected Concurrentqueue<t> queue = new concurrentqueue<t> ();        protected thread thread;        private volatile bool isopened;            public bool Isopened {get {return isopened;        }} public event action<t> Exceute;        public event Action Stopedexceute; <summary>///start thread pool main thread///</summary> public void Start () {if (th Read! = null) {throw new Exception ("The thread pool is already in the boot state!            ");            thread = new Thread (Run); Thread.            Start ();        isopened = thread = null;            }///<summary>///thread pool main thread execution logic//</summary> private void Run () { while (isopened) {T temP Queue.                Trydequeue (out temp);                if (temp! = null) {Raiseexecute (temp);            } else break;            } isopened = false;            thread = NULL;        Raisestopedexceute (); }//<summary>//Trigger Execute Event///</summary>//<param name= "Data" ></p aram> private void Raiseexecute (T data) {Exceute?.        Invoke (data); }///<summary>//Trigger Stop Execute Event///</summary>//<param name= "Data" >< /param> private void Raisestopedexceute () {Stopedexceute?.        Invoke ();            }///<summary>//End thread pool main thread///</summary> public void Stop () {            PostData (Default (T));        isopened = false;     }///<summary>//External submit data object to queue///</summary>   <param name= "Data" ></param> public void Post (T data) {postdata (data); }///<summary>//internal submission of data to thread pool queue///</summary>//<param name= "Data" >&lt ;/param> private void PostData (T data) {queue.        Enqueue (data); public void Dispose () {if (This.thread! = NULL && this.thread.ThreadState! = system.th Reading. threadstate.stopped) {this.            Stop (); }        }    }

Test code:

string[] temp = new string[]            {                "This was 1.",                "this is 2.", "This is 3.", "This is                4.", "This is                5." "," This was 6. "," This is 7. "," This is                8. ",                " this is 9.                "," This is a. "," This is one. "," T He is. "            };            Pool. Exceute + = pool_exceute1;            Pool. Start ();            foreach (string data in temp)            {                pool. Post (data);            }

  

Use of the thread pool for automated control

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.