1. Create a thread
Thread thread = new Thread (new ThreadStart (SortAscending ));
2. Start the thread
Thread. Start ();
3. Terminate the thread
If you want a process to end, one way is to complete the thread's entry function execution, but in many cases this method is not enough to meet the needs of the application.
1) Abort
When the Abort method is called, it will trigger ThreadAbortException to the thread to be terminated, and then the thread is terminated. Example:
Class Program
{
Static void Main (string [] args)
{
Thread thread = new Thread (Run );
Thread. Start ();
Thread. Sleep (1000 );
Thread. Abort ();
Console. WriteLine ("Aborted .");
Console. ReadLine ();
}
Static void Run ()
{
Try
{
Console. WriteLine ("Run executing .");
Thread. Sleep (5000 );
Console. WriteLine ("Run completed .");
}
Catch (ThreadAbortException ex)
{
Console. WriteLine ("Caught thread abort exception .");
}
}
}
Running result
2) Join
The join method blocks the calling thread until the specified Thread stops running.
Static void Main (string [] args)
{
Thread thread = new Thread (Run );
Thread. Start ();
Thread. Sleep (1000 );
Thread. Join ();
Console. WriteLine ("Joined .");
Console. ReadLine ();
}
Www.2cto.com
Static void Run ()
{
Try
{
Console. WriteLine ("Run executing .");
Thread. Sleep (5000 );
Console. WriteLine ("Run completed .");
}
Catch (ThreadAbortException ex)
{
Console. WriteLine ("Caught thread abort exception .");
}
}
}
Running result:
From Enjoy. NET