Let's start by creating a thread that simply provides a thread entry when you create a thread using the thread class. (Thread entry makes the program know what to do with this thread)
In C #, the thread entry is provided through the ThreadStart Proxy (delegate), and you can interpret ThreadStart as a function pointer to the function to be executed by the thread, when the Thread.Start () method is invoked, The thread begins executing the function that the ThreadStart represents or points to.
Open your vs.net, create a new console Application (console application), and write code examples that fully control one thread:
//threadtest.cs
using System;
using System.Threading;
Namespace ThreadTest
{
public class Alpha
{
public void Beta ()
{
while (true)
{
Console. WriteLine ("Alpha.beta is running into its own thread.");
}
}
};
public class Simple
{
public static int Main ()
{
Console.WriteLine ("Threa D start/stop/join Sample ");
Alpha Oalpha = new alpha ();
file://creates a thread here to perform the Beta () method of the Alpha class
Thread othread = new Thread (new ThreadStart (Oalpha.beta)); br> Othread.start ();
while (!othread.isalive)
Thread.Sleep (1);
Othread.abort ();
Othread.join ();
Console.WriteLine ();
Console.WriteLine ("Alpha.beta has finished");
Try
{
Console.WriteLine ("Try to restart the Alpha.beta thread");
Othread.start ();
}
catch (threadstateexception)
{
Console.Write ("Threadstateexceptio n trying to restart Alpha.beta. ");
Console.WriteLine ("Expected since aborted threads cannot be restarted.");
Console.ReadLine ();
}
return 0;
}
}
This program contains two classes Alpha and simple, and we use the initialization of the ThreadStart proxy (delegate) object to the Alpha.beta () method when creating the thread othread. When we create a thread othread invoke the Othread.start () method to start, the program actually runs the Alpha.beta () method:
Alpha Oalpha = new alpha ();
Thread othread = new Thread (new ThreadStart (Oalpha.beta));
Othread.start ();
Then, in the while loop of the main () function, we use the static method Thread.Sleep () to let the main thread stop 1ms, and this time the CPU turns to execute thread othread. Then we tried to terminate the thread Othread with the Thread.Abort () method, noting the Othread.join (), Thread.Join () method, which causes the main thread to wait until the othread thread ends. You can give the Thread.Join () method a parameter of type int as the maximum time to wait. After that, we tried to restart the thread othread with the Thread.Start () method, but obviously the result of abort () method was an unrecoverable terminating thread, so the final program throws ThreadStateException exception.