C # asynchronous programming and its synchronization mechanism
This article covers a few pieces of content:
1. What is asynchronous programming and why does it require asynchronous programming
2.. NET-asynchronous programming and its development
3.. NET thread synchronization mechanism and data marshaling between threads
4. Asynchronous mode
5. Thread safety and exception handling
6. Thread Cancellation
What is asynchronous programming and why does it require asynchronous programming
The resources in this world are limited. But resource constraints, like laziness, have contributed to the development of industry and technology. As an example of computer, does the computer have to be binary? is the binary best for computers? No, this is due to the industrial level at that time, the voltage is divided into two parts to represent 0 and 1 is more convenient and reliable than divided into three parts; virtual memory management, cache and other technologies are driven by the hardware constraints of the technology, the same asynchronous programming and distributed programming is also. Life in a lot of things are not linear, take a common example of the students ' time, the beginning of tomorrow, a lot of homework did not write, so find a classmate homework copy, but in a short period of time a person is very difficult to copy, so I paid a few students to copy, a job to a few people to do, this is asynchronous. But the handwriting is different so do not have a copy of the security, it is possible that the elder brother several copies of a copy of the content repeated several times (thread safety), this period in case of pen, paper, rubber is not ready to have a resource contention, deadlock problem (synchronous problem), the elder brother a few times will also report each other progress (inter-thread , so there is a risk that we have to have a mechanism to avoid this risk, asynchronous programming is similar to this.
Where do you use async in programming? A simple case, graphical interface program, background if you want to connect database queries or write large amounts of data or I/O operations, the interface will be "suspended animation." The reason this happens is that these processes are in the UI thread, and when these operations occupy the UI thread, any action such as dragging the UI, clicking the button, and so on, is not responding in a timely manner. The solution is to put these long operations into a new thread-asynchronous operation, freeing up the UI thread. Other applications such as massive data calculations, server responses to client requests, and so on.
. NET-asynchronous programming and its development
First, the thread can be divided into foreground thread and background thread. The foreground thread is almost as scary as a vampire, and if you want to kill the process, all the foreground processes must be wiped out, and the UI thread is the foreground thread. The background thread is the son of Er Fang, and the process dies immediately after the death, and it is clear that the background thread is the spelling checker of Word, or that Outlook is responsible for synchronizing the messages with the server to update the thread.
Any platform and programming language will have multi-threaded implementation mechanisms and methods. For C #, the thread class is the most initial means of creating threads and managing threads. However, creating and destroying a thread is very resource-intensive, and the more threads you create, the more frequently you switch between threads (the number of computer CPUs is limited), the resource and time that thread switching takes, and thread management is a great worry, so Microsoft introduces a thread pool concept. The thread pool is a FIFO queue, and programmers simply throw operations or tasks to the thread pool, allowing the. NET framework to manage threads for programmers, thread reuse, and so on, greatly simplifying development. Here is an issue that controls the number of threads in the thread pool. Thread Cheng threads are sure to change dynamically as needed, but what is the algorithm that adapts to this need?
A simple algorithm: adding some threads to the thread pool, observing the thread pool throughput, increasing the throughput after increasing the thread is not enough, it is necessary to increase the thread. However, there is a problem with a large task that takes a long time to occupy threads, and increasing the thread does not increase the throughput, at which point the increase in the thread will add to the burden. So the concept of a local queue was introduced when the CLR V4, and if one line range creates another thread, the newly created thread is no longer thrown to the global queue, but instead queues the local queue for invocation. This is another question, what if one queue has finished executing and the other queue has a lot more to do? That allows the local queue to execute the task to "steal" a thread from the queue. This achieves load balancing. Of course, the thread pool algorithm evolves as the CLR version upgrades, managing threads more intelligently. For the average developer, there is no need to consider these details and seamlessly experience the convenience and efficiency of the thread pool.
The thread pool is so convenient, how do we use the thread pool? There are several ways to do this:
Called directly through the class method ThreadPool.QueueUserWorkItem.
A parallel Library of TPL (Task Parallel Library) tasks introduced through the. NET Framework 4.0.
The main two classes in the TPL are task and parallel. The new C + + standard also introduces similar concepts parallel_for, Parallel_foreach, parallel_invoke and so on.
For more information, see the link below.
Called by an asynchronous delegate (Begininvoke/endinvoke).
With BackgroundWorker, BackgroundWorker is WinForm, a control under WPF that is used primarily to provide collaborative cancellation, progress reporting, and so on, under UI controls.
Here I also want to talk about PFX (Parallel FrameWork). PFX can be conceptually divided into data parallelism and task parallelism.
The upper layer consists of two structured data parallel APIs: PLINQ and the parallel class. The underlying task, in parallel, contains the task class and a series of subordinate constructs to help with parallel programming. Note that PFX is built on top of the online pool and is a way to better use the thread pool, with the argument that TPL is more efficient than using the thread pool directly. Please refer to the link for the use of the Plinq,task,parallel class and the listed structure.
. NET thread synchronization mechanism and data marshaling between threads
First of all. What is the synchronization mechanism of net? The profile is for safety. The synchronization mechanism exists because the asynchronous operation is unsafe and brings up a series of problems that have been discussed in the first section. Inter-thread data marshaling and COM, like the. Net Framework data marshaling, are for the delivery of data and state between threads.
So what are the synchronization mechanisms for. NET? To summarize:
Simple Locking method: The Thead class of sleep, join, and the wait method of the task.
Object-based locking:
Lock (Monitor.enter/monitor.exit): First of all, it is not possible to synchronize across interprocess threads. In general, threading synchronization has a feature, that is, the synchronization object has a name.
Mutexes and Semophore (Slim): Both can be synchronized across processes, the difference being that a mutex can have only one wait resource, and Semophore may have multiple. Take the toilet. For example, a mutex is equivalent to only one squat in the toilet, only one can be on the other, and Semophore may have multiple squats, allowing multiple threads to block the execution of a thread at the same time. is n a friend squatting together, and a friend, and then this n a friend to occupy that what is not that.
Reade/writer lock.
3. Signal-based
Event wait handle AutoResetEvent, ManualResetEvent (Slim): Note that these two are also allowed to cross-process, with the same usage, so that one thread releases a signal so that other threads can execute.
Countdownevent (4.0): This is the opposite of the above usage, which causes a thread to wait for the other thread to be signaled before executing.
Barrier
Wait and Pulse
4. Non-blocking synchronization structure
Thread.memorybarrier
Thread.volatileread/write
Interlocaked
Please refer to the following links for specific application of the above synchronization mechanism and demo code.
A good example of data marshaling between threads is that when a button is clicked to start an operation on a new thread, but the execution needs to be displayed on a label, it is necessary to marshal the new line range the data object representing the execution state back to the UI thread. This section can refer to a post I wrote earlier: Http://www.cnblogs.com/salomon/archive/2012/06/28/2567339.html.
Asynchronous mode
What needs asynchronous mode? The so-called pattern, in fact, is a method, as mentioned in the previous blog, is from the engineering practice summed up to solve similar or specific problems of a customary means. Common asynchronous patterns include the following:
APM mode: Beginxxx/endxxx, IAsyncResult
EAP Mode (event-based asynchronous mode)
Windows Form
Methodnameasync
Event
TAP (Task-based asynchronous mode)
Methodnameasync
Task/task<result>
This part of the content of the following link is very good, interested can see. A more detailed introduction to MSDN or the official website to find similar documents.
Thread safety and exception handling
Will the exception thrown in the new thread be automatically marshaled to the main thread? How do I handle exceptions thrown in a new thread? What is thread safety? How do I do thread safety?
Thread cancellation
How can the executing thread not be canceled, how to cancel the appropriate? Violence canceled? Collaborative cancellation?
c#5.0 New Async mode async and await keywords
Please refer to my previous blog: http://www.cnblogs.com/salomon/archive/2012/06/27/2565862.html
Original link: http://www.cnblogs.com/salomon/archive/2012/07/26/2610548.html
This article is from Black Network-China's largest network security site Source Link: http://www.hackbase.com/tech/2012-08-03/66710.html
"Go" C # Asynchronous programming and its synchronization mechanism