C # asynchronous programming and its synchronization mechanism,

Source: Internet
Author: User
Tags net thread

[Switch] C # asynchronous programming and its synchronization mechanism,

C #Asynchronous programming and its synchronization mechanism

This article covers the following parts:

1. What is asynchronous programming and why does it need asynchronous programming?

2. asynchronous programming under. NET and Its Development

3.. NET thread synchronization mechanism and data sending between threads

4. asynchronous mode

5. thread security and Exception Handling

6. Thread Cancellation

What is asynchronous programming? Why?

Resources in this world are limited. However, resource restrictions and laziness promote the development of industry and technology. For example, do computers have to be binary? Is binary the best for computers? No, this is because of the industrial limitations at that time. It is more convenient and reliable to divide the voltage into two parts, which means 0 and 1 are scored into three parts. Virtual Memory Management, cache and other technologies are all limited by the hardware conditions at that time, as are asynchronous and distributed programming. Many things in life are not linear. Let's look at a common example in the student age. I started school tomorrow and did not write a large number of homework. So I asked a student to copy my homework, however, in a short period of time, it was difficult for a person to complete the copy, so I spent money to ask a few students to copy a job and assign it to a few people. This is asynchronous. However, apart from handwriting, no one copied this safely. Maybe some of my colleagues copied one copy of the unit weight several times (thread-safe). During this period, in case of pen, paper, when the erasers are not fully prepared, they still have to compete for resources. The deadlock problem (synchronization problem) will also report the progress of each other (data sending between threads ), so there is a risk in doing this. We have to have a mechanism to avoid this risk. asynchronous programming is similar to this.

Where will asynchronous programming be used? In a simple scenario, the graphic interface program, if you want to connect to the database to query or write massive data or perform I/O operations on the background, the interface will be "suspended ". The reason for this is that these operations are all in the UI thread. When these operations occupy the UI thread, any operations such as dragging the UI and clicking the button will not respond in time. The solution is to put these operations that take a long time into a new thread for asynchronous operations, and release the UI thread. Other applications such as massive data computing and server response to client requests.

Asynchronous programming under. NET and Its Development

First of all, threads can be divided into foreground threads and background threads. The front-end thread and the vampire are almost terrible. To do this, all the front-end processes must be killed. The UI thread is the front-end thread. The background thread is the son of the second-party student. After the process dies, it is obvious that the background thread is the Word spelling check, or outlook is responsible for synchronously updating the mail with the server.

Any platform and programming language will have multi-threaded implementation mechanisms and methods. For C #, the Thread class is the initial method for creating threads and managing threads. However, it is resource-consuming to create and destroy a thread. The more threads you create, the more frequently you switch between threads (limited number of CPUs ), thread switching also consumes resources and time. In addition, thread management is a very laborious task, so Microsoft introduced the concept of thread pool. The thread pool is a first-in-first-out/FIFO queue. Programmers only need to throw operations or tasks to the thread pool, so that. NET framework can manage threads and reuse threads for programmers, greatly simplifying development. There is a question about the number of threads in the thread pool. The threads in the thread pool must change dynamically as needed, but what algorithm is needed?

A simple algorithm: add some threads to the thread pool and observe the throughput of the thread pool. If the throughput increases after the increase, the thread is insufficient and the thread needs to be added. But there is a problem. For a large task that requires a long time to occupy the thread, increasing the thread does not increase the throughput. At this time, increasing the thread will increase the burden. Therefore, the concept of Local Queue is introduced in CLR v4. If another thread is created in one thread, the newly created thread will not be thrown to the global Queue, instead, it queues the local queue for calls. This is another problem. What should I do if the tasks in one queue are completed while there are many tasks in the other queue? Then let the local queue that executes the task "steal" a thread from the queue for execution. This achieves load balancing. Of course, the algorithm of the thread pool will evolve with the upgrade of the CLR version to manage threads more intelligently. For general developers, you don't need to consider these details, so you can seamlessly experience the convenience and efficiency brought by the thread pool.

The thread pool is so convenient. How can we use the thread pool? You can use the following methods:

Directly call ThreadPool. QueueUserWorkItem using the class method.

The TPL (Task Parallel Library) Task Parallel Library introduced through. net Framework 4.0.

The two most important classes in TPL are Task and Parallel. The new C ++ standard also introduces similar concepts such as parallel_for, parallel_foreach, and parallel_invoke.

For more information, see the following link.

It is called through an asynchronous delegate (BeginInvoke/EndInvoke.

Through BackgroundWorker, BackgroundWorker is a control in WinForm and WPF. It is mainly used to provide collaborative cancellation and Progress Report under the UI control.

Here I will also talk about PFX (Parallel FrameWork ). In terms of concept, PFX can be divided into data parallelism and task parallelism.

The upper layer consists of two Structured Data Parallel APIs: PLINQ and Parallel classes. The underlying Task parallelism includes the Task class and a series of ancillary structures to help with parallel programming. Note that PFX is built on the thread pool and is a better way to use the thread pool. It is said that TPL is more efficient than directly using the thread pool. For the PLINQ, Task, and Parallel classes and the listed structures, see the link.

. NET thread synchronization mechanism and data sending between threads

First, what is the synchronization mechanism of. Net? In general, it is for security. Synchronization mechanisms exist because asynchronous operations are insecure and may cause a series of problems that have been discussed in Chapter 1. Data encapsulation between threads is the same as Data encapsulation between COM and. Net framework. It is used to transmit data and status between threads.

So what are the synchronization mechanisms of. net? Summary:

Simple locking method: Sleep, Join of Thead class, and Wait of Task.

Object-based locking:

Lock (Monitor. Enter/Monitor. Exit): first, emphasize that it cannot be synchronized across threads between processes. Generally, a feature of Inter-import thread synchronization is that the synchronization object has a name.

Mutex and Semophore (slim): both of them can be synchronized across processes. The difference between the two is that Mutex can only have one waiting resource while Semophore can have multiple. Taking the restroom as an example, Mutex is equivalent to having only one squat position in the restroom, and Semophore can have more than one squatting position, so that multiple threads can simultaneously block the execution of one thread. That's where n of them are squatting together, and another one is coming, and then the n of them are occupying that.

Reade/Writer lock.

3. Signal-based

Event wait handle AutoResetEvent, ManualResetEvent (Slim): Note that the two allow cross-process operations. The two allow similar usage, so that one thread releases a signal so that other threads can execute.

CountdownEvent (4.0 introduced): This is the opposite of the above usage. It allows a thread to wait until it receives signals from other threads before execution.

Barrier

Wait and pulse

4. Non-blocking synchronization Structure

Thread. MemoryBarrier

Thread. VolatileRead/Write

Interlocaked

For the specific application and Demo code of the above synchronization mechanism, refer to the following link.

For inter-thread data sending, a good example is to click the button to start executing an operation in the new thread, but the execution process needs to be displayed on a label, at this time, the data objects in the new thread that indicate the execution status should be sent back to the UI thread. For more information, see my previous post: http://www.cnblogs.com/salomon/archive/2012/06/28/2567339.html.

Asynchronous mode

What does asynchronous mode need? The so-called mode is actually a method. As mentioned in the previous blog, It is a usual method to solve similar or specific problems summarized from engineering practice. Common asynchronous modes include:

APM mode: BeginXXX/EndXXX, IAsyncResult

EAP mode (Event-based asynchronous mode)

Windows Form

MethodNameAsync

Event

TAP (Task-Based asynchronous mode)

MethodNameAsync

Task/Task <Result>

The link below is quite good. If you are interested, please take a look. For more details, go to the MSDN or official website to find similar documents.

Thread security and Exception Handling

Will exceptions thrown in the new thread be automatically sent to the main thread? How to handle exceptions thrown in the new thread? What is thread security? How to Ensure thread security?

Thread canceled

How can I cancel the thread being executed? How can I cancel it properly? Brute force cancellation? Collaborative cancellation?

C #5.0 new asynchronous mode Async and await keywords

Please refer to my previous blog: http://www.cnblogs.com/salomon/archive/2012/06/27/2565862.html

Link: http://www.cnblogs.com/salomon/archive/2012/07/26/2610548.html

This article from the network-China's largest network security site Source: http://www.hackbase.com/tech/2012-08-03/66710.html

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.