Thread of basic skill training

Source: Internet
Author: User
Tags thread class try catch

During this time, I looked at the basic skills training course of Jin Xu-liang's software development trilogy. Now summarize your knowledge about C # threading, deepen your impressions, and comb your knowledge.

The main operating system now supports multitasking in parallel, and threads are the basic unit on which the operating system allocates CPUs

The split work task can be encapsulated into a thread function that is executed by the thread. The process of running a thread is reflected in the execution of the thread function.

1. Thread constructors

 Public Thread (threadstart start);  Public Thread (parameterizedthreadstart start);

The constructor of a thread is made up of two kinds, one is ThreadStart is a delegate without parameters, no return type

The other is Parameterizedthreadstart, which is a parameter with an object and no delegate of the return type. Both of these delegates are used to hook up the external method, and the function executes when the thread runs

 Public Delegate void ThreadStart ();  Public Delegate void Parameterizedthreadstart (object obj);

2. Three ways to create a thread object and execute it

C # Thread class thread--method with no parameters

  public  void  threadmethod () //  method to be called by thread   {  //  method internal code  }  static  void   Main () { // threadstart is a delegate that has no parameters, no return value, and is used to hook up a method called by a thread  thread th = new  thread ( Span style= "COLOR: #0000ff" >new  ThreadStart (Threadmethod)); //  Create a thread object  th. Start (); //  Call the Start method to run thread } 

 c# Thread class thread--method with the object parameter

 public  void  refreshlable (object   Infovalue) {Action  <string  > del = (string  info) => { //  method internal code };  static  void   Main () {Thread th  = new   Thread (refreshlable); Th. Start (obj);  //  }  

3. Termination of the thread

You can use thread.currentthread in a thread function to get a reference to the threading object that is responsible for executing this function

Terminate the thread prematurely using the AborT method but be aware that a try catch is in the thread method and then call the ResetAbort method otherwise the CLR throws an exception

classProgram {Static voidMain (string[] args) {System.Console.WriteLine ("Main thread Start"); //To create a thread objectMyThread obj =NewMyThread (); Thread th=NewThread (obj.            Somelongtask); Th. IsBackground=true; Th. Start ();//Start ThreadThread.Sleep ( -);//main thread sleeps 0.3 secondsSystem.Console.WriteLine ("The main thread calls the Abort method to abort the worker thread prematurely ..."); Th.  Abort (); //Abort thread prematurelySystem.Console.WriteLine ("Main thread End");        Console.readkey (); }    }    classMyThread { Public voidSomelongtask () {Try{System.Console.WriteLine ("worker thread Start ...");  for(inti =0; I <Ten; i++) {System.Console.WriteLine (i); Thread.Sleep ( $); }            }            Catch(ThreadAbortException e) {System.Console.WriteLine ("The worker thread was prematurely interrupted: {0}", E.message);  Thread.resetabort (); //without this sentence, the CLR will throw ThreadAbortException again, causing the last sentence of the function to not execute.             }            finally{System.Console.WriteLine ("completing cleanup worker thread-occupied resource work"); }            //If there is no previous thread.resetabort (), then the program flow does not execute to this sentence. System.Console.WriteLine ("worker thread End"); }    }

4. Background thread

The Isbackgruoud property is set to true to indicate that the thread is a background thread, and when a thread is set to a background thread, the background thread is automatically interrupted when the main course is finished.

By default, the Isbackgruoud property is false and becomes the foreground thread, and the CLR waits for all foreground threads to end before ending the entire process

5.Join method

Th after the Join method is called, the main thread waits here until the th thread executes and the main thread continues execution

Static void Main (string[] args)        {            Console.WriteLine ("The main thread starts running ")            ; New Thread (new  ThreadStart (Threadamethod));            Th. Start ();            Th. Join ();            Console.WriteLine (" main thread exit ");            Console.readkey ();        }

6. Thread Status

Threads are part of the advanced and very important part, and I'm learning to feel that some places are still somewhat difficult, but interesting. Multi-threaded programs are difficult to debug, and can be difficult to track down after a breakpoint because it starts another thread. This is the initial feeling that I have just come into contact with multi-threaded development.

Previously wanted to learn multi-threading, but the C # Illustrated tutorial directly on the async and await keyword, feeling is not the most basic multithreaded learning, so has been slow to learn, until you see the Golden Teacher's curriculum. Very happy, but also very urgent, because soon to face internships and employment but still feel that their knowledge reserves are not enough. To continue to fight!!

Thread of basic skill training

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.