C # multithreading case Basics

Source: Internet
Author: User

 

Before learning multithreading, let's look at several concepts:

1What is a process?
WhenProgramWhen running, it is a process, including the memory and system resources used by running programs and programs,Of course, a program may also start multiple processes..
A process is composed of multiple threads.

2.What is a thread?
A thread is an execution stream in a program. Each thread has its own proprietary register (Stack pointer, program counter, etc.),CodeZones are shared, that is, different threads can execute the same function.

3What is multithreading?
Multithreading means that a program contains multiple execution streams, that is, a program can run multiple different threads to execute different tasks at the same time, that is to say, a single program is allowed to create multiple parallel threads to complete their respective tasks.

Advantages of multithreading:
CPU utilization can be improved. In a multi-threaded program, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly improves the program efficiency and user experience. A typical multi-threaded application is that when reading a large amount of data from a database, the interface may be suspended and users cannot operate on other content on the interface. Multithreading can solve this problem.

Disadvantages of multithreading:
The thread is also a program, so the thread needs to occupy the memory. The more threads occupy the memory, the more;
Multithreading requires coordination and management, so it requires CPU time to track threads;
Inter-thread access to shared resources will affect each other, and the problem of competing to share resources must be solved;
Too many threads will lead to too complex control, which may lead to many bugs;

Note: Any program must have at least one main thread during execution.

After a program starts from main, the process starts to provide various resources for the entire program. At this time, a thread is started. This thread is the main thread, which schedules resources for specific operations. Thread-enabled threads are subthreads under the main thread, and are parent-child relationships. At this time, the program is multi-threaded. These threads schedule and execute resources together.

 

The thread class has several important methods, which are described as follows:
Start (): Start the thread;
Sleep (INT): a static method that pauses the specified number of milliseconds of the current thread;
Abort (): This method is usually used to terminate a thread;
Suspend (): This method does not terminate the unfinished thread. It only suspends the thread and can be recovered later;
Resume (): resume the execution of threads suspended by the suspend () method;

In plain words, multithreading can allow computers to "do multiple things at the same time" to save time. Multithreading allows a program to "simultaneously" process multiple tasks.

Next we will learn more about multithreading through several cases

 

Multithreading case:

Case 1: execute a method using multiple threads

Class Program

{

Static void main (string []
ARGs)

{

Myclass
Myclass = new myclass ();

Thread
Thread = new thread (New threadstart (myclass. mythread1 ));

Thread. Start ();

Console. writeline (thread. threadstate );

// Note that Readline () cannot be used here. Otherwise, the effect will not appear.

Console. Readline ();

}

}

 

Class myclass

{

Public
Void mythread1 ()

{

Console. writeline ("Hello everyone, I am thread 1 ");

}

}

To explain the above Code, first define a mythread1 method in the myclass class. This method has no parameter and no return value. Then, in the main method, a thread object thread is created through the Thread class, but the constructor needs to input a delegate variable, so the new threadstart (myclass. mythread1) creates a delegate variable. Next, you can use the thread. start () starts the thread. Note that after the start method of the thread is called, the thread is not executed immediately, but is only marked as the thread can be executed, when the thread is executed, the CPU scheduling is required.

Case 2: thread startup method with Parameters

Static void main (string []
ARGs)

{

Thread
Thread = new thread (New parameterizedthreadstart (parameterrun ));

String []
STRs = {"bruce lee", "Gong Li", "Fan Bingbing "};

Thread. Start (STRs );

Console. Readline ();

}

Static void parameterrun (Object
OBJ)

{

Console. writeline ("I Am a thread method with Parameters ");

String []
Arr = OBJ as string [];

Foreach
(String s in
ARR)

{

Console. writeline (s );

}

}

The only difference between this case and Case 1 is that when a thread instance is created, a delegate variable with parameters must be used as a constructor parameter, and methods that comply with the delegate specifications must have no return value, there can be only one parameter, and the parameter type is object. When the parameterrun method parameter value is assigned, it must be done in thread. Start.

Of course, in a real project, it is impossible to use it in such a simple way, but as long as you understand how to use a thread with parameters, complicated problems will be solved.

Case 3: Simulated lottery Program

Public partial class form1: Form

{

Public
Form1 ()

{

Initializecomponent ();

}

 

Private
Thread thread;

// Whether the lottery host is in the Starting Status

Private
Bool isstart = false;

Private
Void btnok_click (Object
Sender, eventargs E)

{

If
(Isstart)

{

Btnok. Text = "start ";

Isstart = false;

}

Else

{

Btnok. Text = "stop ";

Isstart = true;

// Enable a single thread to shake the number to prevent the master thread from being suspended

Thread = new thread (show );

Thread. Start ();

}

}

Public void show ()

{

Random
Random = new random ();

While
(Isstart)

{

Lbl1.text = random. Next (0,
10). tostring ();

Lbl2.text = random. Next (0,
10). tostring ();

Lbl3.text = random. Next (0,
10). tostring ();

// Let the current thread sleep for a while

Thread. Sleep (100 );

}

}

Private
Void form1_load (Object
Sender, eventargs E)

{

// Do not check controls for cross-thread operations

Control. checkforillegalcrossthreadcils
= False;

}

Private
Void form1_formclosing (Object
Sender, formclosingeventargs E)

{

// Close the subthread before closing the form (main thread)

If
(Thread! = NULL)

{

Thread. Abort ();

}

}

}

When writing this program, pay attention to the following points:

1,
In the form load event, set cross-thread operations without checking controls

2,
End sub-thread execution before the main form is closed

3,
To avoid random number living too fast, Use thread. Sleep () to let the thread that generates the random number rest for a period of time.

Of course, we only explain how to use multithreading. If you want to have a deeper understanding of the underlying implementation of multithreading, You need to query more books and materials. Hope this articleArticleIt can help you.

Slight cold rain:

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.