. Net defines multithreading in the system. Threading namespace. Therefore, if your program wants to use multithreading, you must reference this namespace (using system. Threading ).
We know that there are two ways to use multithreading in. Net:
1. Use thread to create a new thread.
2. Use threadpool.
First, let's talk about several concepts related to thread.
1. Create and start a thread. If the code can be implemented
Thread newthread = new thread (New threadstart (work. dowork ));
Newthread. Start ();
Or
Thread newthread = new thread (New parameterizedthreadstart (work. dowork ));
Newthread. Start (42 );
Parameterizedthreadstart this delegate is added in. NET Framework 2.0
When a managed thread is created, the method executed on the thread is represented by a threadstart delegate or parameterizedthreadstart delegate passed to the thread constructor.
This thread will not start execution until the system. Threading. thread. Start method is called. The execution starts from the first line of the method represented by the threadstart or parameterizedthreadstart delegate.
Parameterizedthreadstart delegate and thread. the START (object) method overload makes it easy to pass data to the thread, but because any object can be passed to the thread. start (object), so this method is not of type security.
A more reliable way to pass data to a thread process is to put both the thread process and data fields into the auxiliary object.
The following code example demonstrates the syntax for creating and using parameterizedthreadstart delegation through static and instance methods. The usage of threadstart delegation is the same as that of parameterizedthreadstart,
The only difference is that the threadstart method does not require parameters. (The instance is from msdn)
Using system;
Using system. Threading;
Public class work
{
Public static void main ()
{
// To start a thread using a shared thread procedure, use
// The Class Name and method name when you create
// Parameterizedthreadstart delegate.
//
Thread newthread = new thread (
New parameterizedthreadstart (work. dowork ));
// Use the overload of the Start method that has
// Parameter of type object. You can create an object that
// Contains several pieces of data, or you can pass any
// Reference type or value type. The following code passes
// The integer value 42.
//
Newthread. Start (42 );
// To start a thread using an instance method for the thread
// Procedure, use the instance variable and method name when
// You create the parameterizedthreadstart delegate.
//
Work W = new work ();
Newthread = new thread (
New parameterizedthreadstart (W. domorework ));
// Pass an object containing data for the thread.
//
Newthread. Start ("the answer .");
}
Public static void dowork (Object Data)
{
Console. writeline ("static thread procedure. Data = '{0 }'",
Data );
}
Public void domorework (Object Data)
{
Console. writeline ("instance thread procedure. Data = '{0 }'",
Data );
}
}
/** // * This code example produces the following output (the order
Of the lines might vary ):
Static thread procedure. Data = '42'
Instance thread procedure. Data = 'the ancer'
*/
2. Thread Suspension
Two types of suspended threads are available: active and passive.
Active suspension can be expressed:
Thread. Sleep int32 () or thread. Sleep (timespan) indicates the time at which the current call thread is suspended.
Passive suspension:
Thread newthread = new thread (New threadstart (work. dowork ));
Newthread. Start ();
Newthread. Join ();
Or
Thread. currentthread. Join (50 );
Join indicates that the calling thread is blocked until a thread is terminated while the standard COM and sendmessage message pump processing continues.
In the com thread model indicated by [stathread], we should use thread. currentthread. Join (50. There is a related example,
Thread. Sleep vs. thread. currentthread. Join
3. Terminate the thread.
When you call the abort method to destroy a thread, the common language runtime will trigger threadabortexception. Threadabortexception is a special exception that can be captured, but it will be automatically thrown again at the end of the Catch Block.
When this exception is thrown, the runtime will execute all finally blocks before the program thread. Because the thread can execute unbound computing in the Finally block, or call thread. resetabort to cancel the suspension, it cannot be guaranteed that the thread will end completely.
If you want to wait until the terminated thread ends, you can call the thread. Join method. Join is a modular call that is returned only when the thread actually stops running.
Note: When the Common Language Runtime Library (CLR) stops the background thread after all foreground threads in the managed executable file have ended, it does not use system. Threading. thread. Abort.
Therefore, threadabortexception cannot be used to detect when the CLR terminates the background thread.
The following example shows how to abort a thread. The thread receiving threadabortexception uses the resetabort method to cancel the abort request and continue execution. (The example is from msdn)
Using system;
Using system. Threading;
Using system. Security. permissions;
Public class threadwork {
Public static void dowork (){
Try {
For (INT I = 0; I <100; I ++ ){
Console. writeline ("thread-working .");
Thread. Sleep (100 );
}
}
Catch (threadabortexception e ){
Console. writeline ("thread-caught threadabortexception-resetting .");
Console. writeline ("exception message: {0}", E. Message );
Thread. resetabort ();
}
Console. writeline ("thread-still alive and working .");
Thread. Sleep (1000 );
Console. writeline ("thread-finished working .");
}
}
Class threadaborttest {
Public static void main (){
Threadstart mythreaddelegate = new threadstart (threadwork. dowork );
Thread mythread = new thread (mythreaddelegate );
Mythread. Start ();
Thread. Sleep (100 );
Console. writeline ("Main-aborting my thread .");
Mythread. Abort ();
Mythread. Join ();
Console. writeline ("Main ending .");
}
}
This code generates the following output:
Thread-working.
Main-aborting my thread.
Thread-caught threadabortexception-resetting.
Exception message: thread was being aborted.
Thread-still alive and working.
Thread-finished working.
Main ending.
Note that after. NET Framework 2.0, the suspend and resume methods of the thread object have been abandoned.
The reason is that the suspend and resume methods are used to synchronize thread activity. You cannot know what code it is executing when a thread is suspended.
If you suspend the lock-holding thread during the security permission evaluation, other threads in the appdomain may be blocked.
If you suspend a class constructor when the thread is executing the class constructor, other threads attempting to use the class in the appdomain will be blocked. It is easy to cause deadlocks.