Under the System.Threading namespace, there is a thread class that is used to manage threads, such as creating threads, starting threads, terminating threads, merging threads, letting threads hibernate, and so on.
The thread class (assuming thread firTh = new Thread instance) Firth.isbackground returns a bool value, judging or setting whether it belongs to a background thread
By default, a thread that belongs to the managed thread pool (that is, Isthreadpoolthread true) belongs to a background thread, and all that is generated by creating and starting a new thread object belongs to the foreground thread.
If you use a thread to monitor certain activities (such as sockets), you can set IsBackground to true so that the thread does not affect the process termination.
1. Start thread
thread T1 = new Thread (method name); Creates a thread that executes the specified method through a delegate, starting with the. net2.0, or you need to add ThreadStart
If the method has parameters, it can be passed at startup:
T1. Start (); No reference
T1. Start ("I ' m param"); With parameters
There can be only one parameter, only the object type, and if you want to pass multiple, you can encapsulate all the parameters into a class and then pass an instance of the class.
2. Terminating threads
There are two methods, the first one is to set a bool value beforehand, and the other thread modifies the bool value to indicate whether it needs to be terminated, and in that thread to iterate over the Boolean value to determine whether the thread needs to be exited.
The second is to call the Abort () method, which has the final effect of forcing the thread to terminate. However, the thread does not actually end immediately, because the system will have to do code cleanup before the thread ends, which will take a certain amount of time, so when the abort () method is called, a death-like animation may occur if the automatic cleanup work is not finished. To solve this problem, you can call the join () method in the main thread and specify the wait time for the main thread to wait for the child thread to end in the Join method.
The first method is recommended, and the first method is generally used in practical work.
3. Suspend thread
Thread.Sleep (int milliseconds) This method is a static method
4. Merging threads
T1. Join ();
T2 can be called in T1 if the thread T1 needs to be executed at the end of T2 execution. Join (), but if T2 has not finished executing, then T1 cannot execute, so you can add a parameter to the join:
T1. Join (1000); This allows the T1 to wait at most only 1000 milliseconds, and then continues execution regardless of whether the T2 is finished.
To access a control created by another thread in one thread
Direct Access reports an exception: it is accessed from a thread that is not creating a control. Now there are two ways to do this:
The first is the use of delegates and events to complete.
The second is implemented using the Backroundworker component.
1. Delegation
First, define a delegate inside the class
Then instantiate the delegate where it needs to be used.
Determine whether the control belongs to the thread through the invokerequired of the control and use the delegate or call the required method directly:
Public Partial classForm1:form {Delegate voidToaddsth (stringItem);//defining delegates in a class ... Private voidaddmessage (string item) {Toaddsth Mydele=NewToaddsth (AddMessage);//instantiating a delegate if(textbox1.invokerequired)//determine whether a delegate is required based on the invokerequired of the control{textbox1.invoke (Mydele,item); //using Delegates } Else{TEXTBOX1.ITEMS.ADD (item); //Call directly } } }
volatile modifier
The volatile modifier indicates that the declared field can be modified by multiple threads that execute concurrently. If a field declaration contains volatile, the field is no longer optimized by the compiler, ensuring that it renders at any time the most recent value.
For fields accessed by multiple threads, and the field does not serialize access with the lock statement, it should be declared with volatile.
The volatile modifier can only be included in the declaration of a class or struct, and local variables cannot be declared volatile.
classClass1 { Public volatile BOOLShouldstop; //Here is set to volatile is the key, otherwise can not be timely control, the keyword can not be modified properties, directly with the property can not be controlled in time PrivateForm1 Form1; PublicClass1 (Form1 form) { This. Form1 =form; } Public voidMETHOD1 (Objectobj) { stringmsg = obj as string; while(!shouldstop)//when the switch is turned on and cycle{Thread.Sleep ( -); Form1. AddMessage (msg); } Form1. AddMessage ("Now a stoped!");//Jump out of the loop } Public voidMethod2 () { while(!shouldstop) {Thread.Sleep ( -); Form1. AddMessage ("b"); } Form1. AddMessage ("Now b stoped!"); } }
Public Partial classform1:form {Process Process1=NewProcess (); Delegate voidToaddsth (stringitem); Class1 C1; Thread Th1, Th2; PublicForm1 () {InitializeComponent (); C1=NewClass1 ( This); Button1. Click+=NewEventHandler (button1_click); Button2. Click+=NewEventHandler (button2_click); } Private voidButton1_Click (Objectsender, EventArgs e) {TextBox1.Text=""; Th1=NewThread (C1. METHOD1); Th2=NewThread (C1. METHOD2); Th1. IsBackground=true; Th2. IsBackground=true; Th1. Start ("a start"); Th2. Start (); } Private voidButton2_Click (Objectsender, EventArgs e) {C1.shouldstop=true; } }
[C # Network application programming] 2, thread management