Multi-thread programming in. net

Source: Internet
Author: User

multithreading is a feature of many operating systems. It can greatly improve the running efficiency of Programs , therefore, multithreading programming technology is widely used by programmers. At present, Microsoft's. NET strategy is being further promoted, and various related technologies are accepted by the majority of programmers. Also, multi-threaded programming technology in. Net has a very important position. This article will introduce you to the basic methods and steps for multi-threaded programming under. net.

Start a new thread
in. it is very easy to create a new thread under. You can use the following statement to start a new thread:
thread = new thread (New threadstart (threadfunc);
thread. start ();
the first statement creates a new thread object and specifies a method for this thread. When a new thread starts, this method is called and executed. This thread object calls the thread method to be called through an instance of the system... threading. threadstart class using a type-safe method.
the second statement officially starts the new thread. Once the method start () is called, the thread remains in the "alive" state, you can read its isalive attribute to determine whether it is in the "alive" status. The following statement shows how to suspend a thread in the "alive" State:
If (thread. isalive) {
thread. suspend ();
}

However, note that the START () method of the thread object only starts the thread, and does not guarantee that the thread method threadfunc () can be executed immediately. It only ensures that the thread object can be allocated to the CPU time, and the actual execution is determined by the operating system based on the processor time.

A thread's method does not contain any parameters, nor returns any value. Its naming rules are the same as those for general functions. It can be either static or non-static ). After it is executed, the corresponding thread ends, and the isalive attribute of Its thread object is set to false. The following is an example of a thread method:

Public static void threadfunc ()

{

For (INT I = 0; I <10; I ++ ){

Console. writeline ("threadfunc {0}", I );

}

}

Foreground thread and background thread

. NET Common Language Runtime (CLR) can distinguish two different types of threads: foreground thread and background thread. The difference between the two is that the application can exit only after running all the foreground threads. For background threads, the application can exit without considering whether it has been completed, all background threads automatically end when the application exits.

Whether a thread is a foreground thread or a background thread is determined by its isbackground attribute. This attribute is readable and writable. The default value is false, which means that a thread is the foreground thread by default. We can set its isbackground attribute to true to make it a background thread.

In the following example, a console program starts 10 threads at the beginning, and each thread runs for 5 seconds. Because the isbackground attribute of threads defaults to false, that is, they are all Front-End threads, even though the main thread of the program soon stops running, however, the program will end only when all started threads are completed. ExampleCodeAs follows:

Using system;

Using system. Threading;

Class MyApp

{

Public static void main ()

{

For (INT I = 0; I <10; I ++ ){

Thread thread = new thread (New threadstart (threadfunc ));

Thread. Start ();

}

}

Private Static void threadfunc ()

{

Datetime start = datetime. now;

While (datetime. Now-Start). Seconds <5)

;

}

}

Next, we will slightly modify the above Code and set the isbackground attribute of each thread to true. Then, every thread is a background thread. As long as the main thread of the program ends, the whole program ends. The sample code is as follows:
Using system;

Using system. Threading;

Class MyApp

{

Public static void main ()

{

For (INT I = 0; I <10; I ++ ){

Thread thread = new thread (New threadstart (threadfunc ));

Thread. isbackground = true;

Thread. Start ();

}

}

Private Static void threadfunc ()

{

Datetime start = datetime. now;

While (datetime. Now-Start). Seconds <5)

;

}
}

Since there is such a difference between the foreground thread and the background thread, how do we know how to set the isbackground attribute of a thread? The following are some basic principles: for some threads running in the background, when the program ends, these threads do not need to continue to run, so these threads should be set as background threads. For example, if a program starts a thread that performs a large number of operations, but once the program ends, the thread will lose its meaning to continue to exist, then the thread should be used as the background thread. For some threads that serve the user interface, it is often set as the foreground thread, because even if the main thread of the program ends, other user interface threads are likely to exist to display relevant information, so they cannot be terminated immediately. Here I just give some principles, specific to the actual use often requires further careful consideration by programmers.

Thread priority

Once a thread starts running, the thread scheduler can control the CPU time it receives. If a hosted application runs on a Windows machine, the thread scheduler is provided by windows. On other platforms, the thread scheduler may be part of the operating system or part of the. NET Framework. However, we do not need to consider how the thread scheduler is generated here. We only need to know how to set the thread priority so that the thread can get a different CPU time.

The thread priority is controlled by the thread. Priority attribute. Its values include threadpriority. Highest, threadpriority. abovenormal, threadpriority. Normal, threadpriority. belownormal, and threadpriority. Lowest. From the perspective of their names, we can naturally know their priority, so we will not discuss them here.

The default thread priority is threadpriority. Normal. Theoretically, threads with the same priority will get the same CPU time, but in actual execution, threads in the message queue are blocked or the operating system's priority is increased, which leads to threads with the same priority to get different CPU times. However, this difference can still be ignored in general. You can change the priority of a thread through the following methods.

Thread. Priority = threadpriority. abovenormal;

Or:

Thread. Priority = threadpriority. belownormal;

With the first statement above, you can increase the priority of a thread, so that the thread will get more CPU time; by using the second statement, you reduce the thread's priority, so it will be allocated with less CPU time than the original one. You can change the priority of a thread before it starts running or at any time during its running process. Theoretically, you can set the priority of each thread at will. However, a thread with a higher priority may affect the running of other threads or even the running of other programs, so it is best not to set the thread priority randomly.

Suspending and restarting a thread

The thread class provides two methods respectively to suspend a thread and restart the thread, that is, thread. Suspend can pause a running thread, and thread. Resume can continue to run the thread. Unlike Windows kernel ,. the Net Framework does not record the number of threads suspended. Therefore, no matter how many times you have suspended the thread, you only need to call the thread once. resume can re-run the suspended thread.

The thread class also provides a static thread. Sleep method, which can automatically suspend a thread for a certain period of time and then start again automatically. A thread can call a thread within itself. the sleep method can also call the thread internally. suspend method, but other threads must call its thread. the resume method can be restarted. Is it easy to figure this out? The following example shows how to use thread. sleep:

While (continuedrawing ){
Drawnextslide ();
Thread. Sleep (5000 );
}

Terminate thread
In managed code, you can terminate another thread in one thread using the following statement:
Thread. Abort ();
Next we will explain how the abort () method works. Because the common language manages all managed threads during runtime, it can also throw exceptions in each thread. The abort () method can throw a threadabortexception exception in the target thread, leading to the termination of the target thread. However, after the abort () method is called, the target thread may not be terminated immediately. As long as the target thread is calling unmanaged code and no response is returned, this thread will not be terminated immediately. If the target thread is calling unmanaged code and is in an endless loop, the target thread will not be terminated at all. However, this is only a special case. In more cases, the target thread is calling the hosted code. Once abort () is called, the thread is terminated immediately.

In practical applications, a thread terminates another thread, but it is often necessary to wait until the thread completely terminates it to continue running. In this way, we should use its join () method. The sample code is as follows:

Thread. Abort (); // request to terminate another thread
Thread. Join (); // It continues to run only when the other thread is completely terminated.

However, if another thread cannot be terminated for a long time (as described above), we need to set a time limit for the join () method. The method is as follows:

Thread. Join (5000); // pause for 5 seconds

In this way, after five seconds, the thread runs forcibly regardless of whether the thread is completely terminated. This method also returns a Boolean value. If it is true, it indicates that the thread has been completely terminated. If it is false, it indicates that the time limit has been exceeded.

Clock thread

The timer class in the. NET framework allows you to use the clock thread, which is included in the system. Threading namespace. Its function is to call a thread method after a certain interval. Next I will show you a specific instance, which takes one second as the interval and outputs different strings in the console. The Code is as follows:

Using system;
Using system. Threading;
Class MyApp
{
Private Static bool ticknext = true;
Public static void main ()
{
Console. writeline ("press enter to terminate ...");
Timercallback callback = new timercallback (ticktock );
Timer timer = new timer (callback, null, 1000,100 0 );
Console. Readline ();
}
Private Static void ticktock (object state)
{
Console. writeline (ticknext? "Tick": "tock ");
Ticknext =! Ticknext;
}
}
From the code above, we know that the first function callback occurs after 1000 milliseconds, and the subsequent function callback also occurs after 1000 milliseconds, this is determined by the third parameter in the timer object constructor. The program will continuously generate new threads after the interval of 1000 milliseconds, and the running will only end after the user enters the carriage return. However, although we set the time interval to 1000 milliseconds, the actual operation is often not very accurate. Because the Windows operating system is not a real-time system, and the public Language Runtime is not real-time, due to the ever-changing thread scheduling, the actual running effect is often not accurate to milliseconds, but it is enough for general applications, so you do not have to be very demanding.

Summary
This article introduces some basic knowledge about multi-threaded programming in. net. SlaveArticleWe can know that multi-threaded programming in. NET is much simpler than before, but its function is not weakened. With the above basic knowledge, readers can try to write multi-threaded programs under. net. However, to write multi-threaded applications with more powerful functions and fewer bugs, you need to master advanced multi-threaded programming technologies such as thread synchronization and thread pool. Readers may wish to refer to some technical books on operating systems or multithreading programming.

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.