C # Multithreading Basics

Source: Internet
Author: User

Core content:
1, the necessary space to introduce.
2. Create another thread on the current threads.
3. Run the thread.
4. Suspend thread.
5, thread recovery.
6, the thread waits.
7, thread synchronization.
8, Thread async.
9. End Thread.

Specific implementation:
1, (must) introduce system.threading space.
2. Almost everything in C # is encapsulated into classes, and so is thread, taking the instantiation of a class (defined way).
Note that the parameters of the constructor thread (). The parameter essence is a method. You can either use a delegate or you can put a method instance directly
The Parameterizedthreadstart delegate that comes with it is an array parameter of type object only (that is, you cannot have the Out,ref parameter).
There must be no return value.
Note: Let's take a closer look at the meaning of the phrase "share resources with all threads in the same process": C # is Object-oriented,
Everything is object, so sharing is the access and operation of each object. and the new thread needs to be constructed from a function, so
Access restrictions for classes and classes must be followed. There is no need to focus on how the main thread accesses the private members of the class (he must have this ability, otherwise
How does the program execute? )
In a class, it is particularly important to note that if a class is not instantiated, a function called by a thread cannot run unless a static function or instantiation is used, especially in the console
。 Or instantiate this class first (this is very difficult, the constructor is to pass
New to invoke, and the thread () parameter can only be a method that cannot be a new statement.
3, the new thread is not running, you need to use [thread name]. The Start () parameter is the parameter of the method being called (not filled in).
4, suspend thread, restore, wait, synchronization, generally do not use [instance]. Suspend (); and recovery [instance]. Resume ();
Instead, the AutoResetEvent class is used, which allows threads to communicate with each other by signaling. (The code is equivalent to the "modal form", and its status is false to stop execution of the following
Code) Typically, this communication involves a resource that the thread requires exclusive access to.
The thread waits for a signal by calling WaitOne on AutoResetEvent. If the AutoResetEvent is in a non-terminating state, the thread is blocked,
and waits for the current thread that controls the resource
Sends a signal that the resource is available by calling Set.
Call Set to signal AutoResetEvent to release the waiting thread. AutoResetEvent will remain signaled until a waiting thread is freed and then automatically returned to the non-terminating state. If no thread is waiting, the state remains in the terminating state indefinitely.
You can control the initial state of the AutoResetEvent by passing a Boolean value to the constructor, true if the initial state is signaled, or false.
In layman's terms, only after the successful operation of the Myreseteven.set (), Myreseteven.waitone () will be able to obtain operational opportunities; Set is a signal,
WaitOne is waiting for the signal, only to send a signal,
Wait for it to execute. If not, the program behind WaitOne will never be executed.
This allows for thread control (suspend and resume) and interprocess communication (wait, sync).
You can also use join () to insert a process into another process,
For example, establish a in B, in the execution of A.join (); Indicates that B stops waiting for a, (but remember: there is no effect on a), you can also specify the time, if not specified, until
A execution is complete. (thread synchronization Technology)
5, thread asynchronous, after the creation of each thread is asynchronous
Join () method
6, the end of the thread, the function of the call is finished and end state, can also call Abrot (), but not necessarily can stop;

Several important attributes:
(1) enumeration of ThreadState (read-only)---threadstate
Abroted: Indicates that the thread code has not been executed but has been forcibly exited (stopped)
Abrotrequested: Indicates that Abrot () has been called, but has not been stopped.
Background: Represents a Background thread
Background: Threads are executed in the background, related to attribute thread.isbackground;
Running: thread is running properly;
Stopped: Thread has been stopped;
Stoprequested: Thread is being requested to stop;
Suspended: The thread has been suspended (in this state, it can be rerun by calling the Resume () method);
Suspendrequested: Thread is being requested to be suspended but not responding;
Unstarted: Thread.Start () is not called to start the thread run;
WaitSleepJoin: The thread is blocked by calling wait (), Sleep (), or join ().

(2) IsAlive (read-only)---Indicates whether the code is running (paused, not started, suspended, waiting is inactive)
(3) IsBackground (writable----Indicates whether it is a background program
(4) Priority (writable)--------Precedence, ThreadPriority enumeration, how much time the CPU allocates to the thread.
AboveNormal
BelowNormal
Highest
Lowest
Normal
Relationship: Lowest < BelowNormal < Normal < AboveNormal < highest

-------------------------------------------------------------Code Implementation--------------------------------------------

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading;//Note: Here's what you're going to introduce yourself.6 7 namespaceConsoleApplication18 {9     class ProgramTen     { One         Private StaticAutoResetEvent A; A         Static voidMain (string[] args) -         { -Thread Th1 =NewThread (thread1); theThread Th3 =NewThread (NewThreadStart (THREAD3)); -              -Console.WriteLine ("------------------------First method: Join () block---------------"); - Th1. Start (); +Th1. Join ();//until 1 executes the mainline friend continues -Th1. Abort ();//and a "insurance" . +  AConsole.WriteLine ("------------------------The second method: based on the AutoResetEvent message delivery mechanism---------------"); atA =NewAutoResetEvent (true);//Indicates whether the new start state "mechanism" is turned on.  -             //in fact, in this setting is better, but in order to reflect the usage, here is true equivalent to set (); - Th3. Start (); -              - console.readline (); -         } in  -         /// <summary> to         ///Implementing Join () Usage +         /// </summary> -         Private Static voidThread1 () {//the first thread to run an instance of theConsole.WriteLine ("Thread 1 starts running"); *Thread Th2 =NewThread (NewParameterizedthreadstart (thread2)); $Th2. Start (5);Panax NotoginsengConsole.WriteLine ("thread 1 will be waiting for 2"); -Th2. Join ();//in the asynchronous state, only 2 is executed, and the execution continues . theConsole.WriteLine ("Thread 1 continues to run"); +Th2. Abort ();//ensure that the output of one of the following methods is not affected by interference A         } the  +         Private Static voidThread2 (ObjectN//the first thread to run an instance of -         { $Console.WriteLine ("Thread 2 starts running"+", and passed in the parameter"+ ((int) n). ToString ()); $Console.WriteLine ("Thread 2 is going to hibernate 2s"); -Thread.Sleep ( -); -Console.WriteLine ("Thread 2 continues to run"); the         } -         /// <summary>Wuyi         ///Implementing AutoResetEvent Usage the         /// </summary> -         Private Static voidThread3 ()//Third instance of a thread Wu         { - A.reset ();  AboutConsole.WriteLine ("Thread 3 starts running on"); $Thread Th4 =NewThread (THREAD4); - Th4. Start (); -Console.WriteLine ("thread 3 will be waiting for 4"); - A.waitone (); AConsole.WriteLine ("Thread 3 Recovery run"); +         } the         Private Static voidthread4 () { -Console.WriteLine ("Thread 4 starts running on"); $Console.WriteLine ("thread 4 will stop 1s"); theThread.Sleep ( +); theConsole.WriteLine ("Thread 4 Recovery run"); the A.set (); the         } -  in     } the  the     About}

C # Multithreading Basics

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.