C # Multithreading series (iii)

Source: Internet
Author: User
Tags thread class

thread Pool

It takes time to create a thread, and if you have a different small task to complete, you can create many threads beforehand and make a request when you should complete those tasks. This number of threads is best added when more threads are needed and less when resources need to be freed.

You do not need to create such a list yourself. The list is hosted by the ThreadPool class. This class increases the number of threads in the thread pool until the maximum number of threads is required.

  • You can specify the minimum number of threads that are started immediately when the thread pool is created, and the maximum number of threads available in the thread pool.
  • If more jobs are to be processed, the number of threads in the thread pool is at its limit, the latest jobs are queued, and the threads must wait for their jobs to complete.
  • Threads in the thread pool are background threads and cannot change the pool thread to the foreground thread.
  • You cannot set a priority and a name for a thread that is in the pool.
  • For COM objects, all threads that are pooled are multithreaded apartment threads. Many COM objects require a single-threaded apartment thread.
  • A thread that is pooled can only be used for tasks that are short in time. If a thread is to run all the time, you should create a thread using the thread class.

Static voidMain () {intnworkerthreads; intncompletionporthreads; Threadpool.getmaxthreads ( outNworkerthreads, outncompletionporthreads); //Threadpool.setmaxthreads (a);Lib.print ("Max worker Threads:"+nworkerthreads); Lib.print ("I/O completion threads:"+ncompletionporthreads);  for(intI=0; i<Ten; i++) {ThreadPool.QueueUserWorkItem (jobforathread);  The method is queued for execution. This method executes when the thread pool threads become available. } thread.sleep ( the);}Static voidJobforathread (ObjectState ) {     for(inti =0; i<3; i++) {Console.WriteLine ("Loop {0}, running inside pooled thread {1}", I, Thread.CurrentThread.ManagedThreadId); Thread.Sleep ( -); }}

sample application first to read worker threads and I/o line for follow the ring, call Thread biography hand one WaitCallback class < Span class= "FONTSTYLE0" > Jobforathread () method gives threads in the thread pool.

thread pool after receiving this request, start the first thread. If the line Cheng is running, and There is an idle thread to complete the task,

Asynchronous Delegate

The simplest way to create a thread is to define a delegate and then invoke it asynchronously.

The delegate uses the thread pool to complete the asynchronous task , and the asynchronous delegate ends directly when no foreground thread is running.

Static voidMain (string[] args) {Action Action=NewAction (() =     {         for(intI=0; i< -; i++) {Lib.put ("."); Thread.Sleep (Ten);    }    }); AsyncCallback Calback= (IAsyncResult result) = ={Thread.Sleep ( -); Lib.print (result.    asyncstate);    }; varrs = action. BeginInvoke (Calback,"Begin Invoke");//Thus, an asynchronous delegate is started.    The following is a different way to wait for an asynchronous delegate to complete. //method One, using the EndInvoke method, the method waits until the delegate finishes the task. action.    EndInvoke (RS); //method Two, use the IAsyncResult associated with the wait handle.    You can access the wait handle by using the AsyncWaitHandle property. //This property returns an WaitHandle type object that can wait for the delegate thread to complete its task. parameter is the maximum wait time,//-1 means infinite wait. Returns true if the current instance receives a signal, otherwise false. Rs. Asyncwaithandle.waitone ( the); //method Three, keep checking     while(true)    {        if(!Rs. iscompleted) {Thread.Sleep ( -); }        Else        {             Break; }    }    //because callback is ultimately an asynchronous thread callback, if you exit directly, callback will not be able to print the begin Invoke. Thread.Sleep ( $);}
Task

System.Threading.Tasks contains classes that abstract out threading functionality and use ThreadPool in the background. A task represents a unit of work that should be completed, the unit works in a separate thread, or it can initiate a task synchronously, which requires waiting for the main thread. Using a task not only gives you an abstraction layer, but also gives you a lot of control over the underlying thread.

    • Start a task

You can use the instantiated TaskFactory class, where the Taskmethod () method is passed to the Starnew () method, and the task is started immediately. You can also use the constructor of the task class. When instantiating a task object, the task does not run immediately, but instead specifies the created state. It then calls the start () method of the task class to start the task. You can also call the tunsynchronously () method when you use the task class.

Static voidMain (string[] args) {Task T1=NewTask (Doonfirst); T1.    Start (); TaskFactory TF=NewTaskFactory (); Task T2=TF.    StartNew (Doonfirst); Task T3=Task.Factory.StartNew (Doonfirst); Task.waitall (T1, T2, T3);}Static voidDoonfirst () {Lib.print ("Task.currentid:"+Task.currentid); Lib.print ("-----------"); Thread.Sleep ( +);}

    • Continuous tasks

A continuous task is defined by invoking the ContinueWith () method class on the task. Without the Taskcontinuationoptions parameter, the successor task starts regardless of how the previous task ended. You can also use the value in the Taskcontinuationoptions enumeration to specify under what circumstances the continuous task will start.

Static Objecto =New Object(); Static voidMain (string[] args) {CancellationTokenSource cs=NewCancellationTokenSource (); Task T1=NewTask (Doonfirst, CS. Token); Task T2=t1. ContinueWith (Doonsecond, taskcontinuationoptions.onlyonrantocompletion); //t1 when complete, start T2 Task T3=t1. ContinueWith (Doonthird, taskcontinuationoptions.onlyoncanceled); //t1 is canceled when the T3 is started Try{t1. Start (); //cs. Cancel (); //opens the comment, cancels the T1, and executes the doonthird. //cs. Token.throwifcancellationrequested (); } Catch{lib.print ("t1. IsCanceled:"+t1. IsCanceled); } console.readkey (); } Static voidDoonfirst () {Lock(o) {lib.print ("Task.currentid:"+Task.currentid); Lib.print ("-----------"); Thread.Sleep ( +); } } Static voidDoonsecond (Task t) {Lock(o) {lib.print ("Task"+ T.id +"finished."); Lib.print ("This task ID"+Task.currentid); Lib.print ("-----------"); Thread.Sleep ( +); } } Static voidDoonthird (Task t) {Lock(o) {lib.print ("Task"+ T.id +"Canceld."); Lib.print ("This task ID"+Task.currentid); Lib.print ("-----------"); Thread.Sleep ( +); } }

Task Hierarchy

Tasks can also form a hierarchy. When a task starts a new task, a parent/child hierarchy is started.

The result of the task

At the end of the task, you can write some useful state information to the shared object. You can also return this information using the task that returns the results.

Static void Main (string[] args) {    Task<intnew task<int> ((Object o) =>{return111"");    T1. Start ();    T1. Wait ();    Lib.print (t1. Result);     New Task (doparenttask);    T.start ();}

C # Multithreading series (iii)

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.