C # Multithreading Case Basics

Source: Internet
Author: User

C # Multithreading case base (GO)

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

1 , what is a process?
When a program starts running, it is a process that includes the memory and system resources used by the programs and programs that are running, and of course a program may open multiple processes .
And a process is made up of multiple threads.

2. What is a thread?
A thread is a flow of execution in a program, each with its own proprietary register (stack pointers, program counters, and so on), but the code area is shared, meaning that different threads can execute the same function.

3 , what is multithreading?
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.
Benefits of Multithreading:
can improve CPU utilization. In multithreaded programs, when a thread has to wait, the CPU can run other threads instead of waiting, which greatly increases the efficiency of the program and, of course, improves the user experience. The typical application of multithreading is that when reading large amounts of data from a database, it causes the interface to suspend animation and the user cannot manipulate other content on the interface. and using multithreading can solve this problem.
The disadvantage of Multithreading:
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 affects 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;

Note: There is at least one main thread for any program to execute.

After a program starts from main, the process starts, providing a variety of resources for the entire program, and a thread is started, which is the main thread, which dispatches resources for specific operations. Thread-Open threads are child threads under the main thread, which is a parent-child relationship, at which point the program is multithreaded, and these threads work together to schedule and execute resources.

The thread class has several critical methods, which are described below:
Start (): Start thread;
Sleep (int): Static method that pauses the specified number of milliseconds for the current thread;
Abort (): This method is usually used to terminate a thread;
Suspend (): The method does not terminate the unfinished thread, it simply suspends the thread and can be resumed later;
Resume (): Restores the execution of the thread that was suspended by the suspend () method;

In terms of easy-to-understand words, multithreading can make the computer "at the same time" multiple things, save time. Multithreading allows a program to "simultaneously" handle multiple things.

Let's take a few examples to learn more about multithreading

Multi-threaded case:

Case 1: Executing a method through multithreading

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 here with ReadLine () can not be used readkey otherwise can not appear effect

Console.ReadLine ();

}

}

Class MyClass

{

public void MyThread1 ()

{

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

}

}

Explain the above code, first define a MyThread1 method in the MyClass class, the method has no parameter no return value. Then in the main method, a thread object is created through the thread class, but a delegate variable is required in its constructor, so a delegate variable is created with new ThreadStart (MYCLASS.MYTHREAD1). Then you can pass the thread. Start () starts the thread, and it is important to note that the thread is not executed immediately after invoking the start method of thread, but simply marked as the thread can execute, and when the thread executes, it needs to obey the CPU's dispatch.

Case 2: Thread initiation 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 threading 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 you create a thread instance, you need a delegate variable with parameters as a parameter to the constructor, and the method that conforms to the delegate specification must not have a return value and only have one argument, and the parameter type is object. The Parameterrun method parameter is assigned when the thread is required. Start ().

Of course, in real projects, the use of the impossible is not so simple, but as long as the understanding of the use of parametric threads, then complex problems will be solved.

Case 3: Simulation of the Lottery machine program

public partial class Form1:form

{

Public Form1 ()

{

InitializeComponent ();

}

private thread thread;

Whether the draw machine is a startup state

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;

Open a single line Cheng number, avoid the main thread suspended animation

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 cross-threading operations on controls

Control.checkforillegalcrossthreadcalls = false;

}

private void Form1_formclosing (object sender, FormClosingEventArgs e)

{

Close a child thread before the form closes (main thread)

if (thread!=null)

{

Thread. Abort ();

}

}

}

When writing this program, you need to note several points:

1, the control's cross-threading operation is set in the Load event of the form without checking

2, end the execution of the child thread before the main form closes

3, in order to avoid random number of life speed too fast, use Thread.Sleep (), let generate random number of threads to rest for a period of time

Of course, we are only explaining how to use multi-threading, and if you want to have a deeper understanding of the underlying implementation of multithreading, you need to query more books and materials. I hope this article will be of some help to you.

C # Multithreading Case Basics

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.