Multithreading study Note 1

Source: Internet
Author: User

1. Multithreading

(1) process: a basic concept in a Windows system. It contains a runningProgramThe required resources are relatively independent among processes. A process cannot directly access the data of another process (unless distributed computing is used ), failure of a process does not affect the running of other processes. In Windows, the process is divided into multiple independent regions, and the process can be understood as the basic boundary of a program.

1) problems to be solved: in order to allow concurrent execution of the Program (for concurrent processing, it is necessary to isolate the process and make the process independent. That is, each process has its own data segment and program segment, process control block)

2) A process is a resource used to isolate different applications.

3) process demo,CodeAs follows:

Static void main (string [] ARGs)

{

// Operation process: getcurrentprocess reads the current process

Console. writeline (process. getcurrentprocess ());

// Obtain all processes in the operating system

VaR process = process. getprocesses ();

Foreach (VAR item in process)

{

// Output the names of all operating systems

Console. writeline (item. processname );

}

// Start the process of an application

Process. Start ("iexplore.exe", "http://www.cnblogs.com/hanyinglong ");

VaR P = process. Start ("notepad.exe ");

// Kill a thread

Thread. Sleep (3000 );

P. Kill ();

}

(2) thread: The thread is the execution stream of a code segment.

1) It is the minimum unit for Windows Task Scheduling. A thread is an execution stream in a program. Each thread has its own proprietary register (such as the stack pointer and program counter ), but the code zone is shared, that is, different threads can execute the same function.

2) solution: a process is the owner of a resource, because the system must pay a large cost for itself during process creation, revocation, and switching, further improvement of concurrent programs

3) A process can have multiple threads.

4) The core switch of CPU is thread

5) Operating System: a cpu can only execute one thread, multiple cores at a time,

6) when the operating system switches the thread, it needs to save all the thread resources and statuses.

7) When a thread is created, the thread control block (1 MB), thread stack, and thread register are required.

(3) differences between managed code and unmanaged code

(4) thread Demo: Create a console application. The Code is as follows:

Namespace threaddemo {// the code of the current program is the class program {static void main (string [] ARGs) executed on the main thread) {// print the information of the current main thread currentthread = thread. currentthread; // print the ID of the main thread. managedthreadid is a unique ID of the hosting thread. writeline ("the current default main thread ID is" + currentthread. managedthreadid); // create a thread and pass a threadstart parameter. If this parameter is transferred to the definition, you can see that it is a delegate. // create a thread object, there is no real allocation thread threaddemo = new thread (threaddemomethod); // only when this method is called, the operating system thread is actually told to be ready, the operating system must allocate threads and execute threaddemo. start (); // start the thread to execute the console. writeline ("main thread execution ends"); console. readkey ();} static void threaddemomethod () {console. writeline ("another thread is executing, thread ID is {0}", thread. currentthread. managedthreadid );}}}

The execution result of this Code is:

The ID of the current default main thread is 1

Main thread execution ends

Another thread is executing. The thread ID is 3.

(5) application domain

1) it provides secure and universal processing units, and the Common Language Runtime Library (CLR) can be used to provide isolation between applications. You can run several application domains in a single process with the same isolation level (in a separate process, without causing additional overhead for inter-process calls or inter-process switching, the ability to run multiple applications within a process significantly enhances server scalability.

2) The application domain contains a heap with memory allocation, and provides a code security boundary (the code between the two application domains is isolated from each other), providing exception handling.

3) one application domain can run multiple threads

4) A thread can only run in one application domain at a time, but an application domain can have multiple threads at the same time.

5) application domain demo

Static void main (string [] ARGs)

{

// Print the current application domain

Console. writeline (appdomain. currentdomain. friendlyname );

// Create an application domain

Appdomain domaindemo = appdomain. createdomain ("Han Yinglong ");

// Enable the current application domain to start and execute an EXE program (one EXE can be executed, but multiple Assembly dll can be executed)

// Step 1: copy the EXE file and PDF file from other projects and put them under our project

// Step 2: Right-click the EXE file copied above and copy it to the output directory to always copy

Domaindemo. executeassembly ("lottery host .exe ");

}

6) execution result ,:

(6) Detailed description of simple threads

1) thread scheduling is performed by the operating system. Our operations are only recommended.

2) threaddemo. isbackground = true;

-> Set a type of the current thread. The default value is the foreground thread.

-> "True" indicates setting a background thread. After the current thread is closed, the current process is closed directly.

-> False indicates setting a foreground thread,

3) thread setting demo

Class program {static void main (string [] ARGs) {thread threaddemo = new thread (demothreadmethod); // sets the priority of the current thread, only the operating system is recommended, give me the current thread, with a higher priority than threaddemo. priority = threadpriority. highest; // if it is set to a foreground thread, threaddemo will be launched only after the current thread is executed. isbackground = true; threaddemo. start (); thread. sleep (3000); // close the thread // threaddemo. abort (); // block the thread currently executing this code and wait until the thread completes threaddemo. join (1000); // name the thread threaddemo. name = "Thread"; console. writeline ("main thread execution completed");} static void demothreadmethod () {While (true) {console. writeline (datetime. now. tostring ());}}}

(7) Description of threads with Parameters

1) parameterizedthreadstart execution Method

-> View reflect: Public Delegate void parameterizedthreadstart (Object OBJ );

2) threads do not return values for delegation, because we do not know when the thread will end.

3) demo of a thread with Parameters

Class Program

{

Static void main (string [] ARGs)

{

// Start a thread with Parameters

Thread threaddemo = new thread (demoparamets );

// Pass parameters to the method specified by the thread

// An array can be passed.

Threaddemo. Start ("Han Yinglong ");

Thread. Sleep (2000 );

Console. readkey ();

}

Static void demoparamets (Object Data)

{

Console. writeline (data. tostring ());

}

}

4) view the above Code in reflect ::

2. How to access controls in a thread

(1) Create a New winform application named multithread and add a text box control and a button to the new winform.

(2) Demo code

Public partial class form1: FORM {public form1 () {initializecomponent (); // if no value is specified, this error is returned: The Inter-thread operation is invalid: it is accessed by a thread that does not create the control "txtmsg. // There is another way to solve the problem. control will be mentioned below. checkforillegalcrossthreadcils = false;} private void btnthread_click (Object sender, eventargs e) {// This is a method of writing // new thread () => // {// txtmsg. TEXT = datetime. now. tostring ();//}). start (); // thread = new thread (changetxt); thread. start ();} public void changetxt () {txtmsg. TEXT = datetime. now. tostring ();}}

3. Use delegation to implement data interaction between two interfaces

(1) create a winform program, use the form1 form as the main form, and create a new form as the subform, add a button and a Textbox Control to the parent form. Add a button control and a Textbox Control to the child form. The project style is following:

(2) the code in the main form is as follows: public partial class form1: FORM {public form1 () {initializecomponent (); // If no code is written, this error is reported: The Inter-thread operation is invalid: it is accessed by a thread that does not create the control "txtmsg. // There is another way to solve the problem. control will be mentioned below. checkforillegalcrossthreadcils = false;} private void btnthread_click (Object sender, eventargs e) {While (true) {thread = new thread (changetxt); thread. start () ;}} public void changetxt () {txtmsg. TEXT = datetime. now. tostring ();} private void btnstart_click (Object sender, eventargs e) {// use delegation to implement frmchild FRM = new frmchild (); // Add the application of the current main form to this frm. parentfrm = This; frm. aftertxtchange = new settextdel (settext); frm. show () ;}// Add a method to assign public void settext (string Str) {txtmsg to the control of the main form. the code in the text = STR ;}} (3) subform is as follows: // use delegate to implement this function Public Delegate void settextdel (string Str); Public partial class frmchild: FORM {// defines the variable public form1 parentfrm for a parent form; // defines the instance public settextdel aftertxtchange for a delegate class; Public frmchild () {initializecomponent ();} private void btnparent_click (Object sender, eventargs e) {string childtxt = txtchildmsg. text; // method 1 //// synchronize the value to the main form. // This. parentfrm. settext (childtxt); // The second method aftertxtchange (childtxt );}}

(4) implementation result:

4. Summary

(1) Why multithreading?

1) Let the computer "do multiple things at the same time" to save energy.

2) multithreading allows a program to "simultaneously" process multiple tasks.

3) running the program in the background improves the running efficiency of the program and does not respond to the primary interface.

(2) Four Steps to generate a thread

1) Compile the method to be executed by the production thread.

2) introduce the system. Threading namespace.

3) instantiate the Thread class and pass in a delegate pointing to the method to be run by the thread (the thread has been generated but has not yet run ).

4) Call the start method of the thread instance to mark that the thread can be executed by the CPU, but the specific execution time is determined by the CPU.

(3) Pay attention to the problem of "method re-entry"

1) The so-called method re-import is a concept related to multi-threaded programming. When multiple threads in a program run simultaneously, the same method may be called by multiple threads at the same time, when some non-thread-safe code exists in this method, method re-entry will result in data inconsistency, which is a serious bug.

(4) processes and threads

1) A process must have at least one thread.

2) "concurrent" execution can be performed between multiple threads in the same process.

3) a thread is an execution stream in a program. Each thread has its own proprietary register (Stack pointer, program counter, etc.), but the code zone is shared, that is, different threads can execute the same function. Multithreading means that a program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks (CODE) at the same time ), that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks.

(5) foreground and background threads

1) Foreground thread: the program can be closed only when all foreground threads are closed.

2) Background threads: Only all foreground threads end and background threads end automatically.

(6) How to Implement multithreading in. Net?

1) The thread must also execute a piece of code. To generate a thread, you must first write a method for the thread. The code in this method is the code that the thread runs to execute (find someone to do this)

2) This method is called by delegation when the thread starts. (when the thread starts, the delegate passed in will execute the corresponding code to implement the method of thread execution ).

(7) Some members of the thread class

1) Start () start thread

2) Abort () Terminate the thread

3) thread. Sleep (100) static method, which can stop the current thread for a period of time.

4) Name thread name

5) thread. currentthread gets the current thread reference

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.