C # multithreaded programming (1)-threads, thread pools, and tasks

Source: Internet
Author: User

A new series of multithreaded programming has been opened that focuses on multithreaded programming in C #. There are 2 purposes of multithreading: one is to prevent UI threads from being consumed by time-consuming programs, causing the interface to lag, and the ability to utilize multi-core CPU resources to improve operational efficiency.

I did not carry out very in-depth explanation, is the actual use mainly. My series is primarily a summary of the CLR via C #, the book's author Jeffrey Richter is a C # consultant, and he himself is very insightful about Windows. In particular, the multi-threaded part, the book is very thorough explanation, the text does not explain or you want to know more in-depth students, you can find the "CLR via C #" careful study.

When a program executes for a long time, such as fetching data from the server, the client waits while the program executes, waits for the program to complete, and then executes other code. If the UI program, the user will feel the interface lag, affecting the use of experience. We hope that such a program can "sneak" in the background run, do not affect the interface. To solve this problem, multiple threads are used, and some of the threads are responsible for responding to interface operations, while others are responsible for background computing. The code is as follows:

public void GetData ()
{ varnew Thread (() = Loaddatafromserver ()); Thread.Start ();}
public void Loaddatafromserver () {
Analog Data Read
Thread.Sleep (2000);
Console.WriteLine ("Read complete. ");
}

The thread is the one you created, and then you call the start () method, and the thread starts executing, loaddatafromserver () is the method you want to execute, and this is where the data is read from the service, and Windows is responsible for scheduling the thread. Decide when this thread will start executing. This allows the new thread to be responsible for reading the data, the main thread does not wait, continue execution, the interface is not Kaka. This is good because it is asynchronous and the interface is smooth, but this is not the optimal solution. When the program executes for a long time, every time the data is read from the server, a new thread is created in order not to cause the interface to stutter. When the data is loaded, the new thread is useless. The creation of a thread is expensive (the cost is not introduced, interested in the Internet to check the relevant information, "CLR via C #" in a very detailed introduction), if each time the created thread is not released after the end of the run, but save it, leave a use, so that you can save resources? The thread pool is doing this, as in the following example:

// Some operations ThreadPool.QueueUserWorkItem (() =loaddatafromserver ()); // Other Operations

As you can see, the previous code did not create the thread explicitly, but instead put the method into the ThreadPool.QueueUserWorkItem () method, ThreadPool is responsible for creating and managing the thread. When the program starts, ThreadPool is called for the first time, when the line constructor a thread does not, the line pool create a new thread, when the program calls the thread pool again, if the line Cheng there are idle threads, then call the idle thread execution program directly, if the program calls the thread pool, Thread pool creates a new thread when there are no idle threads in the pool and the CPU is in an "unsaturated" state. In fact, when the thread pool is called, the thread pool is called to perform the tasks in the thread pool task queue when the CPU is in an "unsaturated" state, which is equivalent to "hanging" the method to be executed on the task queue of the online pool.

One problem with the ThreadPool.QueueUserWorkItem () method is that there is no convenient way to get the return value of the method, not knowing when the Loaddatafromserver () method is done. To solve this problem, C # introduces task, and generic task<t>. The code is as follows

var data = Task.run (() = Loaddatafromserver ()). Result;

First, Task.run () is the encapsulation of the ThreadPool.QueueUserWorkItem () method, which returns a task and can then be called by the task. Result to get the return value of Loaddatafromserver (). In fact, this code does not execute asynchronously, because the thread that the data is on is waiting for the return value of Loaddatafromserver (), otherwise the data will have no value and the program cannot execute, so the thread is blocked and the thread will continue to execute until the task is completed. To address this problem, C # introduces Async and await two keywords. The code is as follows:

 Public Async void LoadData () {    var data = await Task.run (() = Loaddatafromserver ());
Console.WriteLine (data);}
public string Loaddatafromserver () {
Analog to server read data
Thread.Sleep (2000);
return "Data";
}

C # Specifies that the await keyword can only be used in methods marked with async, which compiles the code behind the await into a state machine, and after the Loaddatafromserver () method executes, the program re-enters the LoadData () method, And proceeds from the await, the keyword does not block the thread (how the compiler compiles an await async method into a state machine, which is explained in detail in the CLR via C # 28.4 section).

The above is the first part of multithreaded programming--thread, ThreadPool and task, the next section will continue to explain the other features and methods of the task.

C # multithreaded programming (1)-threads, thread pools, and tasks

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.