Let's move on to create a thread, and when you create a thread using the thread class, you simply provide the thread entry. The thread entry lets the program know what to do with the 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 that the thread is going to execute. When the Thread.Start () method is called, the thread begins executing the function that ThreadStart represents or points to.
Open your vs.net, create a new console Application (console application), and the following code will give you the pleasure of fully controlling a thread!
ThreadTest.cs
Using System;
Using System.Threading;
Namespace ThreadTest
{
public class Alpha
{
public void Beta ()
{
while (true)
{
Console.WriteLine ("Alpha.beta is running in its own thread.");
}
}
};
public class Simple
{
public static int Main ()
{
Console.WriteLine ("Thread start/stop/join Sample");
Alpha Oalpha = new alpha ();
//Create a thread here to perform the Beta () method of the Alpha class
Thread othread = new Thread (new ThreadStart (Oalpha.beta));
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 ("ThreadStateException try ing to restart Alpha.beta. ");
Console.WriteLine ("Expected since aborted threads cannot be restarted.");
Console.ReadLine ();
}
return 0;
}
}
}
This program contains two classes of alpha and simple, and we initialized the ThreadStart agent (delegate) object with a pointer to the Alpha.beta () method when we created the thread othread. When we create the thread Othread call Othread.start () method starts, 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 thread othread. We then tried to terminate the thread Othread with the Thread.Abort () method, noting that the Othread.join () and Thread.Join () method behind it would cause the main thread to wait until the othread thread ended. You can assign a parameter of type int to the Thread.Join () method as the maximum time to wait. After that, we tried to restart thread othread with the Thread.Start () method, but apparently the abort () method had the consequence of an unrecoverable terminating thread, so the final program throws a ThreadStateException exception
The above is the multithreading mechanism of C # (2) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!