A probe into the multithreading mechanism of C # (1)

Source: Internet
Author: User
I. The concept of multithreading

Windows is a multitasking system, and if you are using Windows 2000 and later, you can view the programs and processes that are running on the current system through Task Manager. What is a process? When a program starts running, it is a process that refers to the memory and system resources that are used by the programs and programs that are running. And a process is composed of multiple threads, the thread is an execution flow in the program, each thread has its own proprietary registers (stack pointers, program counters, etc.), but the code area is shared, that is, different threads can execute the same function. Multithreading refers to a program that contains multiple execution streams, in which multiple different threads can be run concurrently to perform different tasks, that is, allowing a single program to create multiple threads of parallel execution to accomplish their tasks. Browser is a good example of multithreading, in the browser you can download Java applets or images while scrolling the page, when accessing new pages, play animation and sound, print files and so on.

The advantage of multithreading is that it can improve CPU utilization--no one programmer wants his program to be dry in many cases, and in a multithreaded program, the CPU can run other threads instead of waiting, which greatly increases the efficiency of the program.

However, we must also recognize that the thread itself may affect the detrimental aspects of system performance in order to use the thread correctly:

Threads are also programs, so threads need to consume memory, and more threads consume more memory
Multithreading requires coordination and management, so CPU time is required to track threads
Access to shared resources between threads can affect each other, and the issue of competing shared resources must be resolved
Too many threads can lead to too much control and can eventually cause many bugs

Based on the above understanding, we can have a metaphor to deepen our understanding. Assuming that there is a company with a lot of staff in the company, then we can assume that the normal operation of the company is a process, and the company's staff is the thread. A company has to have at least one clerk. In the same vein, a process consists of at least one thread. In the company, you can do all the work of a clerk, but the efficiency is obviously not high, a person's company can not be bigger; A program may also use only one thread to do things, in fact, some outdated languages such as fortune,basic, but like a person's company, the efficiency is very low, If you make a big program, it's less efficient-virtually no single-threaded commercial software. The more staff of the company, the more the boss will have to pay them, but also to spend a lot of energy to manage them, to reconcile their contradictions and interests; the same is true of the process, the more threads consume more resources, the more CPU time is needed to track the threads, and the problems such as deadlock, synchronization, etc. are resolved. In short, if you don't want your company to be called a "bag company," You'll have a few more employees, and if you don't want your program to look childish, introduce multithreading into your program!

This paper discusses the multithreading mechanism in C # programming, through some examples to solve the problem of threading control, multithreading communication and so on. In order to avoid the tedious steps of creating a GUI, and to more clearly approximate the nature of the thread, all of the following programs are console programs, and the final console.readline () of the program is designed to stop the program halfway in order to see the output during execution.

Okay, nonsense, let's experience the multi-threaded C #!

Two. Manipulating a thread

Any program at the time of execution, at least one main thread, the following small program can give the reader an intuitive impression:

[CODE]
SystemThread.cs
Using System;
Using System.Threading;

Namespace ThreadTest
{
Class Runit
{
[STAThread]
static void Main (string[] args)
{
Thread.currentthread.name= "System thread";//named "System thread" for the current thread
Console.WriteLine (thread.currentthread.name+ "' Status:" +thread.currentthread.threadstate);
Console.ReadLine ();
}
}
}
[/code]

What did you see after compiling the execution? Yes, the program will produce the following output:

System Thread ' s status:running

Here, we get the currently executing thread through the static property of the thread class, assign the "System Thread" to its Name property, and finally output its current state (ThreadState) CurrentThread. A static property is a property that is common to all objects of this class, no matter how many instances of the class you create, but the static properties of the class are only one in memory. It is easy to understand why CurrentThread is static--although multiple threads exist at the same time, at some point the CPU can only execute one of them.

As the above program demonstrates, we create and control threads through the thread class. Notice the head of the program, we use the following namespaces:
[CODE]
Using System;
Using System.Threading;

[/code]
In the. NET Framework class library, all classes related to multithreaded application are placed in the System.Threading namespace. The thread class is provided for creating threads, the ThreadPool class is used to manage the thread pool, and so on, and also provides a mechanism for solving practical problems such as thread execution scheduling, deadlock, and inter-thread communication. If you want to use multi-threading in your application, you must include this class. The thread class has several critical methods, which are described below:

Start (): Start thread
Sleep (int): Static method, pauses the number of milliseconds specified by the current thread
Abort (): This method is typically used to terminate a thread
Suspend (): This method does not terminate an unfinished thread, it simply suspends the thread and can be resumed later.
Resume (): Restore the execution of a thread that was suspended by the suspend () method

The above is the multithreading mechanism of C # (1) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.