Use threads and thread processing
It is very easy to create, manage, and destroy the trust thread, but if you do not understand the relationship between the tube thread and the non-routine thread and ThreadAbortexception, this may result in an unexpected side effect.
Create thread [C #]
When you create an operating system process, the operating system will insert a thread to perform the code in this process (including any original application domain). From this moment, you can create and destroy the application domain without having to create or destroy any operating system threads. If the code being executed is hosting code, you can get the thread object in the current application domain in the current application domain by retrieving static properties on the thread.currentthread.
When you create a new instance of the Thread object, you will create a new hosting thread. The constructor of Thread uses ThreadStart as its unique parameter, which is used to package the way to call Thread.Start. THREAD.START will trigger ThreadStateException multiple times.
Thread.Start submits asynchronous requests to the system, and this call may return immediately before the new thread actually starts. You can determine the status of threads at any of this at any time using Thread.ThreadState and Thread.isalive. Thread.abort abort the thread and labeled it to carry out garbage collection. The following code example creates two new threads to invoke instances and static methods on another object.
[Visual Basic]
Imports system
Imports system.threading
Public Class ServerClass
'The Method That Will Be Called When The Thread is Started.
Public Sub InstanceMethod ()
Console.writeline ("ServerClass.instancethod is Running on Another Thread.")
Thread.sleep (3000) 'Pause for a Moment to Provide a delay to make threads more apparent.
Console.writeline ("The Instance Method Called by The Worker Thread Has Ended.")
End Sub 'InstanceMethod
Public Shared Sub StaticMethod ()
Console.Writeline ("ServerClass.StaticMethod is Running on Another Thread.")
Thread.sleep (5000) 'Pause for a Moment to Provide a delay to make threads more apparent.
Console.writeline ("The Static Method Called by The Worker Thread Has Ended.")
End Sub 'StaticMethod
End Class' ServerClass
Public Class Simple
Public Shared Sub Main ()
Console.writeline ("Thread Simple Sample")
DIM ServerObject As New ServerClass ()
'Create The Thread Object, Passing in The ServerObject.instanceMethod Method
'Using A Threadstart Delegate.dim InstanceCaller As New Thread (New ThreadStart (Addressof ServerObject.instanceth))
'Start the thread.
Instancecaller.Start ()
Console.writeline ("The Main () Thread Calls this After Starting The New Instancecaller Thread.")
'Create The Thread Object, Passing In the ServerObject.StaticMethod Method
'Using A Threadstart Delegate.
Dim Staticcaller As New Thread (New ThreadStart (Addressof ServerClass.StaticMethod)
'Start the thread.
Staticcaller.Start ()
Console.writeline ("The Main () Thread Calls this After Starting The New StaticCaller Threads.")
End Sub 'Main
End Class' Simple
[C #]
Using system;
Using system.threading;
Public class serverclass {
// The Method That Will Be Called When The Thread is Started.
Public void instanceMethod () {
Console.writeline ("Serverclass.instancethMethod Is Running on Another Thread.");
// Pause for a Moment to provide a delay to make threads more apparent.
Thread.sleep (3000);
Console.writeline ("The Instance Method Called By The Worker Thread Has Ended.");
}
Public static void staticmethod () {
Console.writeline ("ServerClass.StaticMethod Is Running On Another Thread.");
// Pause for a Moment to provide a delay to make threads more apparent.
Thread.sleep (5000);
Console.writeline ("The Static Method Called By The Worker Thread Has Ended.");
}
}
Public class simple {
Public static int main (string [] args) {
Console.WriteLine ("Thread Simple Sample");
ServerClass ServerObject = New ServerClass ();
// Create The Thread Object, Passing In The ServerObject.instanceMethod Method
// using a threadstart delegate.
Thread Instancecaller = New ThreadStart (ServerObject.instanceMeth); // Start The Thread.
Instancecaller.start ();
Console.writeline ("The Main () Thread Calls this After Starting The New Instancecaller Thread.");
// Create The Thread Object, Passing In The ServerObject.StaticMethod Method
// using a threadstart delegate.
Thread staticcaller = new thread (New ThreadStart (ServerClass.StaticMethod);
// Start the thread.
StaticCaller.Start ();
Console.Writeline ("The Main () Thread Calls this After Starting The New StaticCaller Threads.");
Return 0;
}
}
Important, threads can also call methods with parameters, even though ThreadStart entrusts only one parameter - indicates the status of the object. It is this object to transmit parameters to the called method. The following simple code example illustrates a method of transmitting parameters using a status object.
[Visual Basic]
Imports system
Imports system.threading
Public Class SimpleThread
Delegate Sub Start (O as Object)
Private class args
Public o as object
Public s as start
Public SUB WORK ()
s (o)
End Sub 'Work
END CLASS 'ARGS
Public Shared Function CreateThread (S as Start, Arg As Object) AS Thread
DIM A as new args ()
A.O = arg
A.s = s
DIM T As New Thread (Addressof A.Work)
Return T
End function 'CreateThread
End Class' SimpleThread
Class worker
Public Shared Sub WorkerMethod (o As Object)
Console.writeline ("Workermethod:" O.Tostring ())
End Sub 'WorkerMethod
End Class' Worker
Public Class Work
Public Shared Sub Main ()
Dim t as thread = simplethread.createthread (Addressof worker.workermethod, 51)
T.Start ()
T.Join (Timeout.infinite)
End Sub 'Main
End Class' Work
[C #]
Using system;
Using system.threading;
Public class SimplethRead {
Public Delegate Void Start (Object O);
PRIVATE CLASS ARGS {
PUBLIC OBJECT O;
Public START S;
Public void Work () {s (o);
}
}
Public Static Thread CreateTHREAD (Start S, Object Arg) {
Args a = new args ();
A.O = arg;
A.s = S;
Thread T = New Thread (New ThreadStart (a.work));
Return T;
}
}
Class worker {
Public Static Void WorkerMethod (Object O) {
Console.writeline ("WorkerMethod:" O);
}
}
Public class work {
Public static void main () {
Thread T = SimpleThread.createthread (New SimpleThread.Start (Worker.WorkerMethod), 51);
T.Start ();
T.join (Timeout.infinite);
}
}
Pause and continue thread
After starting the thread, you usually want to pause the thread a fixed time. The call thread.sleep will immediately block the current thread for a period of time (this time is the number of milliseconds passing to the SLEEP) and supplies the remainder of its time slice to another thread. A thread cannot call another thread Sleep. Call thread.sleep (Timeout.infinite) will cause threads to sleep until it is called another thread of Thread.Iterrupt or stopped by Thread.abort.
You can also pause a thread by calling thread.suspend. This call will block when threads call Thread.Suspend, until the thread is continued by another thread. When a thread calls Thread.Suspend to another thread, the call is a non-blocking call to another thread. Calling thread.Resume will make another thread out of the suspend state and keep the thread continue to execute, and the number of times called thread.suspend is not related. For example, if you call Thread.Suspend five times, then call thread.resume, the thread will continue to execute immediately after the call to Resume.
Different from thread.sleep, Thread.Suspend does not stop the thread immediately. The public language runtime must wait until the thread reaches the security point, it can hang the thread. If the thread has not started or has stopped, it will not hang.
Suspend and resume methods are not useful for all applications and should not be confused from the synchronization mechanism. Since Suspend and Resume do not rely on collaboration of controlled threads, they have highly violated and lead to serious application issues, such as deadlocks (for example, if the resource required to have another thread, This situation). Some applications do need to control the priority of the thread to improve performance. In order to do this, you should use Thread.Priority instead of thread.suspend.
You can use many ways to block the thread. For example, a thread can wait for another thread to stop by calling thread.join. You can use Monitor.Wait to wait for a thread to access a synchronization object, you can also use thread.sleep to make the thread sleep. Thread.interrupt can be invoked by the blockped thread to interrupt the waiting thread, so that the thread is jumping out of the blocking call. The thread should capture ThreadInterruptedException and perform the appropriate operation to continue. If the thread ignores the exception, the runtime will capture the exception and stop the thread. If you wait a hosted waiting, Thread.Interrupt and Thread.abort will immediately wake up the thread. If the waiting is a non-managed waiting (for example, a platform call call to the Win32 WAITFORSINGLEOBJECT function), both INTERRUPT and ABORT cannot be controlled to the thread until it returns or calls to the managed code. In the hosted code:
Thread.Interrupt wakes threads from what it may be in, and trigger ThreadInterruptedException in the target thread.
Thread.abort is similar to Thread.Interrupt, except that it triggers ThreadAbortexception. This exception is a special exception that cannot be captured from the hosted code (although the Finally block is executed).
Destroy the thread [C #]
Thread.abort method is used to permanently stop logic threads. When calling Abort, the public language runtime will trigger ThreadAbortexception. Threads can capture this exception, but cannot cancel it. The runtime will execute the Catch block and any Finally block, and if the thread is a managed thread, the system will quietly stop the thread without notifying the user.
Since Thread.abort does not cause threads to be aborted immediately, if you need to make sure the thread is stopped, you must call Thread.join to wait on the thread. Join is a blocking call that will not return until the thread is actually stopped. Once thread is aborted, it will not be able to restart.
You can also call thread.join and pass the timeout period. If the thread dies before the end of the timeout, the call will return to TRUE. Otherwise, if the time expires before the thread death, the call will return false. Waiting on the call to thread.join, the thread that can be called through Thread.Iterrupt.
ThreadAbortexception
ThreadAbortException can occur anywhere in the hosted code. However, they happen only at thread.abort or appdomain.unload with sufficient privileges or appdomain.unload. The best way to handle them is to have enough Finally or Catch clauses to maintain consistent status when you have to exit. If necessary, the privileged code that causes ThreadAbortexception will capture and reset it.
The following C # code example is incorrect.
[C #]
Try {
// INSERT Code That Throws an exception.
} catch (exception e) {
// INSERT The First Part of Backout Code Here.
// <--- threadabortexception thrown by the system <-
}
... // Additional Backout Code Here.
To work the previous code, you must move the additional exit code into the CATCH block or put it in the Finally block. This is because after entering the Catch block, ThreadAbortException is implicit by the system, regardless of whether it is handled in this block. In other words, although you can capture ThreadAbortexception, you can't cancel it - it will be automatically re-raised as needed. Explicitly unless one of the unique ways is to call Thread.ResetAbort, and this requires appropriate privileges. You should do this only when you first cause ThreadAbortexception. Scheduling thread
Each thread has a thread priority assigned to it. The priority of threads originally assigned in the public language running library is ThreadPriority.Normal. Threads created outside of the run library remain priority before entering the managed environment. You can use the Thread.Priority property to get or set up any thread priority.
The thread is executed based on its priority. Even if the thread is executing in the run, all threads are allocated by the operating system. The details of the scheduling algorithm used to determine the order of threads are different from each operating system. Under certain operating systems, the thread with the highest priority (relative to the executable thread) is always running after the schedule is scheduled. If multiple threads having the same priority are available, the program program will traverse the thread in this priority and provide a fixed time sheet for each thread. As long as the thread with higher priority can be run, the thread having a lower priority will not be executed. If there is no longer running thread on a given priority, the plan program will move to the next lower priority and scheduled threads on this priority. If a thread having a higher priority can be run, the thread having a lower priority will be first first and allows threads with higher priority to execute again. In addition, the operating system can also dynamically adjust the thread priority when the user moves between the user interface between the application and the background. Other operating systems can choose to use different scheduling algorithms.
to sum up
The above is the basic concepts and sample code in VS.NET. Net thread calls, sorted out to give you a reference. If you have any suggestions, please Mil I Paulni@citiz.net.