The multi-Threading of C # Secret weapons--basic

Source: Internet
Author: User
Tags try catch

I. OverviewWhat is a process?

When a program starts running, it is a process that includes the memory and system resources that are used by the programs and programs that are running. And a process is made up of multiple threads.

What is a thread?

A thread is a flow of execution in a program, each with its own proprietary register (stack pointers, program counters, and so on), but the code area is shared, meaning that different threads can execute the same function.

What is multithreading?

Multithreading refers to a program that contains multiple execution streams, in which multiple different threads can be run concurrently to perform different tasks, that is, allowing a single program to create multiple threads of parallel execution to accomplish their tasks.

Benefits of Multi-threading:

can improve CPU utilization. In multithreaded programs, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly increases the efficiency of the program.

The disadvantage of multi-threading:

Threads are also programs, so threads need to consume memory, more threads consume more memory, multithreading needs to be coordinated and managed, CPU time is required to track threads, access to shared resources between threads affects each other, the problem of competing shared resources must be resolved, too many threads can cause control to be too complex, May eventually cause a lot of bugs;

second,. The Multithreading in net1. Creating Threads

We can use the constructor of the thread class to create the thread, using the parameterless Theadstart delegate or the Parameterizedtheadstart delegate with one parameter as the constructor argument. Thread execution is actually executing the thread function inside-that is, the inside of the delegate function!

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

Give me a chestnut:

Static voidMain () {Thread T=NewThread (NewTheadstart (Go)); //Thread t = new Thead (Go);T.start (); }  Static voidGo () {Console.Write ("hello!"); }  Static voidMain () {Thread T=NewThread (Go); T.start ("Hello");  Go (); }  Static voidGo (Objectmsg) {      stringMessage = (string) msg;  Console.Write (message); }  
2. Start Thread

Start (): Changes the state of the current thread to threadstate.running.

Once the thread is in the threadstate.running state, the operating system can schedule its execution. The thread starts execution from the first line of the method (represented by the ThreadStart or Parameterizedthreadstart delegate provided to the thread constructor). Once the thread terminates, it cannot be restarted by calling start again.

3. Thread Sleep
Thread.Sleep (int  ms); Thread.Sleep (TimeSpan timeout);

The above method is a two static method of the thread class that is used to block the time specified by the current thread.

4. Terminating Threads

Implemented by using the Abort method, which is used to permanently stop a managed thread. Once the thread is aborted, it cannot be restarted. Abort throws a ThreadAbortException exception and can pass a terminating parameter information.

Thread.Abort (); Thread.Abort (Object  stateInfo);

Note: Suspend and resume are obsolete methods, do not use!

5. Thread Properties5.1. Thread name

Each thread has a Name property that can be set and modified, but can only be set once.

5.2. Background thread

In. NET threads are divided into foreground and background threads, and in one process, when all foreground threads stop running, the CLR forces the end of any background thread that is still running, and these background threads are terminated directly without throwing an exception. So we should do what we really want to do in the foreground thread!

Static voidMain (string[] args) {Thread T=NewThread (Test); T.isbackground=true; //here the thread is a background thread and the application ends immediately//if it's a foreground thread, it'll end in about 5 seconds.T.start (); Console.WriteLine ("A");}Static voidTest () {Thread.Sleep (5* +); Console.WriteLine ("B");}
5.3. Thread Priority

The priority of a thread is set or fetched using precedence, and only works at run time, divided into 5 levels:

enum Threadpriority{lowest, BelowNormal, Normal, AboveNormal, highest}

Give me a chestnut:

Mythread.priority=threadpriority.lowest;

Note : higher-priority threads take up more CPU time. However, when a high-priority thread is waiting for some resources, a low-priority thread can run.

6. Blocking Threads

The method used to block a thread is join (). This method allows concurrent processing to be serialized, allowing the main thread to wait until a certain execution is complete before proceeding!

classtest{Static voidMain () {Thread T=NewThread (Run);        T.start (); //join is equivalent to embedding the Run method in thisT.join (); //damn it, T. Join (), my main thread must not be executed until you have finished executing it. Console.WriteLine ("I am the main thread:"+Thread.CurrentThread.GetHashCode ()); }    Static voidRun () {//Wait 5sThread.Sleep ( the); Console.WriteLine ("I am a thread:"+Thread.CurrentThread.GetHashCode ()); }}
7. Exception Handling for Threads

Thread exceptions are resolved in the inline function, so you should put the try catch in the thread's delegate function ~

Static voidMain (string[] args) {      Try      {          NewThread (Go).      Start (); }      Catch(Exception ex) {Console.Write (ex).      Message);  } console.readkey (); }  Static voidGo () {Try     {            ///processing Logic    }   Catch(Exception e) {console.write (e.message); }  }  

Note: When calling the Abort method to terminate a thread, the exception is handled in order to prevent the program from throwing an exception, it is best to add thread.resetabort () after the exception is processed inside the catch.

The multi-Threading of C # Secret weapons--basic

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.