C # Learning (8)

Source: Internet
Author: User

Let's move on to create a thread, and when you create a thread using the thread class, you simply provide the thread entry. (Thread entry lets the program know what to do with this thread.)

In C #, thread portals are provided through the ThreadStart Proxy (delegate), and you can interpret ThreadStart as a function pointer that points to the function that the thread is going to execute when the Thread.Start () method is called. The thread starts executing the function that ThreadStart represents or points to.

code example:

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 ();
FILE://Create a thread here that executes 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 trying 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 result of the Abort () method was an unrecoverable terminating thread, so the final program throws a ThreadStateException exception.

Main thread main () function

All threads are attached to the thread where the main () function is located, and the main () function is the entry for the C # program, which can be called the main thread. If all foreground threads are stopped, the main thread can be terminated, and all background threads will be terminated unconditionally. All threads are executed serially at the micro level, but on the macro level you can think of them as being executed in parallel.

Thread.threadstate Property

This property represents the runtime state of a thread, and in different cases there are different values, and sometimes we can design the program flow by judging the value.

The value of the ThreadState property is as follows:

Aborted: Thread has stopped;

AbortRequested: The thread's Thread.Abort () method has been called, but the thread has not stopped;

Background: Threads are executed in the background, related to attribute thread.isbackground;

Running: thread is running properly;

Stopped: Thread has been stopped;

Stoprequested: Thread is being requested to stop;

Suspended: The thread has been suspended (in this state, it can be rerun by calling the Resume () method);

Suspendrequested: Thread is being requested to be suspended but not responding;

Unstarted: Thread.Start () is not called to start the thread run;

WaitSleepJoin: The thread is blocked by calling wait (), Sleep (), or join ().

The above mentioned that the background status indicates that the thread is running in the background, so what is the special place for the threads running in the background? In fact, the background thread has only one difference from the front thread, that is, the background thread does not prevent the program from terminating. Once all foreground threads of a process are terminated, the CLR (Common language Runtime) terminates the process completely by invoking the abort () method of any surviving background process.

Priority of the thread

When the threads compete for CPU time, the CPU is given the service according to the priority of the thread. In C # applications, users can set 5 different priorities, from high to low, respectively, to Highest,abovenormal,normal,belownormal,lowest, and if you do not specify a priority when creating a thread, Then the system defaults to Threadpriority.normal.

To assign a priority to a thread, we can use the following code:

Set priority to lowest

Mythread.priority=threadpriority.lowest;

By setting the priority of the thread, we can schedule some relatively important threads to take precedence, such as the response to the user, and so on.

C # Learning (8)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.