Event-based Asynchronous Pattern Overview Event-based asynchronous mode Overview, Asynchronous

Source: Internet
Author: User

Event-based Asynchronous Pattern Overview Event-based asynchronous mode Overview, Asynchronous

Https://msdn.microsoft.com/zh-cn/library/wewwczdw (v = vs.110). aspx

Applications that perform extends tasks simultaneously, yet remain responsive to user interaction, often require a design that uses multiple threads.
A multi-thread design is usually required for applications that execute multiple tasks at the same time and interact with users.
The System. Threading namespace provides all the tools necessary to create high-performance multithreaded applications,
The System. Threading namespace provides all the necessary tools to create efficient multi-threaded applications.
But using these tools extends tively requires significant experience with multithreaded software engineering.
However, the effective use of these tools requires rich experience in using multi-threaded software engineering.
For relatively simple multithreaded applications, the BackgroundWorker component provides a straightforward solution.
Compared with simple multi-threaded applications, the BackgroundWorker component provides a simple solution
For more sophisticated asynchronous applications, consider implementing a class that adheres to the Event-based Asynchronous Pattern.
For more complex and non-application scenarios, you can consider implementing a class that supports the event-based asynchronous mode.

The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding beyond the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you:
The event-based one-step mode utilizes the advantages of multi-threaded applications and hides the complex problems inherent in multi-threaded design. Using classes that support this mode ensures that you:
1. Perform time-consuming tasks, such as downloads and database operations, "in the background," without interrupting your application.
Execute time-consuming tasks in the background, such as downloading or database operations, but your application will not be interrupted
2. Execute multiple operations simultaneously, stopping ing configurations when each completes.
Execute multiple operations at the same time. When each operation is completed, receive notifications.
3. Wait for resources to become available without stopping ("hanging") your application.
Wait for resources to be available and your application will not be stopped
4. Communicate with pending asynchronous operations using the familiar events-and-delegates model.
Use the familiar event delegation mode to communicate with pending asynchronous operations

 

A class that supports the Event-based Asynchronous Pattern will have one or more methods named MethodNameAsync.
A class that supports event-based asynchronous mode has one or more methods named according to the rule of method name + suffix Async.
These methods may mirror synchronous versions, which perform the same operation on the current thread.
These methods may all have the corresponding synchronization version and have the same operation on the current thread.
The class may also have a MethodNameCompleted event and it may have a MethodNameAsyncCancel (or simply CancelAsync) method.
This class may also have an event with the method name + Completed suffix, or a method with the method name + AsyncCancel suffix (or CancelAsync directly ).

 

PictureBox is a typical component that supports the Event-based Asynchronous Pattern.
PictureBox is a typical component that supports event-based asynchronous mode.
You can download an image synchronously by calling its Load method, but if the image is large, or if the network connection is slow, your application will stop ("hang ") until the download operation is completed and the call to Load returns.
You can call the Load method to synchronously download an image. However, if the image is too large or the network speed is too slow, your application will stop responding (or suspension ), it is returned after the download operation is completed and the Load method is called.

 

If you want your application to keep running while the image is loading, you can call the LoadAsync method and handle the LoadCompleted event, just as you wocould handle any other event.
If you want your application to download images while running, you can call the LoadAsync method and process the LoadCompleted event.
When you call the LoadAsync method, your application will continue to run while the download proceeds on a separate thread ("in the background ").
When you call the LoadAsync method, your application can continue to run, and the download will start on an independent thread (background)
Your event handler will be called when the image-loading operation is complete, and your event handler can examine the AsyncCompletedEventArgs parameter to determine if the download completed successfully.
Your event processor will be called when the image download operation is complete. The event processor can check the AsyncCompletedEventArgs parameter to determine whether the download is successful.

 

The Event-based Asynchronous Pattern requires that an asynchronous operation can be canceled, and the PictureBox control supports this requirement with its CancelAsync method.
The event-based asynchronous mode must ensure that an asynchronous operation can be canceled. The PictureBox control supports this requirement through its CancelAsync method.
Calling CancelAsync submits a request to stop the pending download, and when the task is canceled, the LoadCompleted event is raised.
Call CancelAsync to submit a request to stop the download operation. When the task is canceled, the LoadCompleted event is triggered.

 

Note:
It is possible that the download will finish just as the CancelAsync request is made, so Cancelled may not reflect the request to cancel.
There is a possibility that the download will be completed when you just called CancelAsync, And the Cancelled In the event parameter may not reflect canceled
This is called a race condition and is a common issue in multithreaded programming.
This phenomenon is called a race condition, which is a common problem in multi-thread programming.

 

 

Characteristics of the Event-based AsyncChronous Pattern features based on the Event-based one-step mode
The Event-based Asynchronous Pattern may take several forms, depending on the complexity of the operations supported by a particle class.
Event-based asynchronous mode may have multiple forms of representation, depending on the complex program for the operations supported by a specific class
The simplest classes may have a single MethodNameAsync method and a corresponding MethodNameCompleted event.
The simplest class only has one MethodNameAsync method and one corresponding MethodNameCompleted event.
More complex classes may have several MethodNameAsync methods, each with a corresponding MethodNameCompleted event, as well as synchronous versions of these methods.
More complex classes have multiple MethodNameAsync methods, and each method has a corresponding MethodNameCompleted event. In addition, these asynchronous methods also have corresponding Synchronization Methods.
Classes can optionally support cancellation, progress reporting, and incremental results for each asynchronous method.


An asynchronous method may also support multiple pending CALS (multiple concurrent invocations), allowing your code to call it any number of times before it completes other pending operations.
Asynchronous methods may support multiple pending calls (multiple concurrent calls), allowing you to call this method multiple times before it completes other pending operations.
Correctly handling this situation may require your application to track the completion of each operation.
To handle this situation, your application is required to track the progress of each operation.

 

  • 1. Example of Examples of the Event-based AsyncChronous Pattern Event-based asynchronous mode

The SoundPlayer and PictureBox components represent simple implementations of the Event-based Asynchronous Pattern.
The SoundPlayer component and the PictureBox component represent a simple implementation of the event-based asynchronous mode.
The WebClient and BackgroundWorker components represent more complex implementations of the Event-based Asynchronous Pattern.
The WebClient component and the BackgroundWorker component represent more complex implementation of the event-based one-step mode.
Below is an example class declaration that conforms to the pattern:
The following is a declaration of an example class conforming to this pattern:

 

public class AsyncExample    {        // Synchronous methods.        public int Method1(string param);        public void Method2(double param);        // Asynchronous methods.        public void Method1Async(string param);        public void Method1Async(string param, object userState);        public event Method1CompletedEventHandler Method1Completed;        public void Method2Async(double param);        public void Method2Async(double param, object userState);        public event Method2CompletedEventHandler Method2Completed;        public void CancelAsync(object userState);        public bool IsBusy { get; }        // Class implementation not shown.    }

The fictitious AsyncExample class has two methods, both of which support synchronous and asynchronous invocations.
The fictional AsyncExample class has two methods, both supporting synchronous and asynchronous calls.
The synchronous overloads behave like any method call and execute the operation on the calling thread;
Synchronous Overloading is performed on the calling thread just like any other method call.
If the operation is time-consuming, there may be a noticeable delay before the call returns.
If this operation is time-consuming, there will be a significant latency before the method returns
The asynchronous overloads will start the operation on another thread and then return immediately, allowing the calling thread to continue while the operation executes "in the background ."
Asynchronous overload will execute the operation on another thread and return immediately. when the operation is executed in the background, the calling thread is allowed to continue the execution.

 

  • 2. AsyncChronous Method Overloads Asynchronous Method overload

There are potentially two overloads for the asynchronous operations: single-invocation and multiple-invocation.
For asynchronous operations, there are two potential reloads: one call and multiple calls
You can distinguish these two forms by their method signatures: the multiple-invocation form has an extra parameter called userState.
You can identify these two forms by using their method signatures. Multiple calls have an additional parameter called userState.
This form makes it possible for your code to call Method1Async (string param, object userState) multiple times without waiting for any pending asynchronous operations to finish.
Multiple calls make sure that the following operations are possible: Your code can call the Method1Async (string param, object userState) method multiple times without waiting for the end of the suspended Asynchronous Operation
If, on the other hand, you try to call Method1Async (string param) before a previous invocation has completed, the method raises an InvalidOperationException.
On the other hand, if you try to call the synchronous method Method1Async (string param) again before the previous call is complete, this synchronous method will trigger an invalid operation exception.

The userState parameter for the multiple-invocation overloads allows you to distinguish among asynchronous operations.
The multiple-call overload parameter userState allows you to differentiate different asynchronous operations.
You provide a unique value (for example, a GUID or hash code) for each call to Method1Async (string param, object userState ),
Each time you call the Method1Async (string param, object userState) method, you can pass a unique value to this method (such as GUID or hash code)
And when each operation is completed, your event handler can determine which instance of the operation raised the completion event.
When each operation is completed, your event processor can determine which operation instance triggers the completion event based on this unique value.

 

  • 3. Tracking Pending Operations

If you use the multiple-invocation overloads, your code will need to keep track of the userState objects (task IDs) for pending tasks.
If you use multiple call reloads, your code needs to use the userState object (Task Number) to track pending tasks.
For each call to Method1Async (string param, object userState), you will typically generate a new, unique userState object and add it to a collection.
Every time you call the Method1Async (string param, object userState) method, you usually need to generate a new and unique userState object and add it to a combination.
When the task corresponding to this userState object raises the completion event, your completion method implementation will examine AsyncCompletedEventArgs. UserState and remove it from your collection.
When a task that matches this userState object triggers a completion event, you need to check AsyncCompletedEventArgs. UserState and remove it from the set to implement your completion method.
Used this way, the userState parameter takes the role of a task ID.
In this way, the userState parameter plays the role of the task number.

Note:
You must be careful to provide a unique value for userState in your callto multiple-invocation overloads.
When you call multiple call reloads, you must be careful enough to provide a unique value for userState.
Non-unique task IDs will cause the asynchronous class throw an ArgumentException.
If the task id is not unique, the asynchronous class throws a parameter error.

 

  • 4. Canceling Pending Operations cancel the Pending operation

It is important to be able to cancel asynchronous operations at any time before their completion.
Before completing asynchronous operations, it is important to ensure that asynchronous operations can be canceled at any time.
Classes that implement the Event-based Asynchronous Pattern will have a CancelAsync method (if there is only one asynchronous method) or a MethodNameAsyncCancel method (if there are multiple asynchronous methods ).
A class that implements the event-based asynchronous mode will have a CancelAsync method (if there is only one Asynchronous Method) or a MethodNameAsyncCancel method (if there are multiple asynchronous methods)

Methods that allow multiple invocations take a userState parameter, which can be used to track the lifetime of each task.
Multiple method calls with the userState parameter can be used to track the lifecycle of each task.
CancelAsync takes a userState parameter, which allows you to cancel particle pending tasks.
The CancelAsync method has a userState parameter to ensure that you can cancel a specified suspended task.

Methods that support only a single pending operation at a time, like Method1Async (string param), are not cancelable.
Only one separate Method of suspension is supported at a time, just like Method1Async (string param), which cannot be canceled.

 

  • 5. Keep ing Progress Updates and Incremental Results to receive Progress Updates and Incremental Results

A class that adheres to the Event-based Asynchronous Pattern may optionally provide an event for tracking progress and incremental results.
Classes that conform to the Event-based asynchronous mode provide events to track progress and incremental results.
This will typically be named ProgressChanged or MethodNameProgressChanged, and its corresponding event handler will take a ProgressChangedEventArgs parameter.
An event is usually named ProgressChanged or MethodNameProgressChanged, and a ProgressChangedEventArgs event parameter corresponds to the event processor.

The event handler for the ProgressChangedevent can examine the ProgressChangedEventArgs. ProgressPercentage property to determine what percentage of an asynchronous task has been completed.
The event processor of ProgressChangedevent can check the percentage of asynchronous tasks completed through the ProgressChangedEventArgs. ProgressPercentage attribute.
This property will range from 0 to 100, and it can be used to update the Value property of a ProgressBar.
This attribute ranges from 0 to 100. It can be used to update the Value Attribute of the progress bar.
If multiple asynchronous operations are pending, you can use the ProgressChangedEventArgs. UserState property to distinguish which operation is reporting progress.
If multiple asynchronous operations are suspended, you can use the ProgressChangedEventArgs. UserState attribute to identify which operation is reporting progress.

Some classes may report incremental results as asynchronous operations proceed.
Some classes can report incremental results while performing asynchronous operations
These results will be stored in a class that derives from ProgressChangedEventArgs and they will appear as properties in the derived class.
The result is saved in a class derived from ProgressChangedEventArgs. the incremental result appears as an attribute of the derived class.
You can access these results in the event handler for the ProgressChanged event, just as you wocould access the ProgressPercentage property.
You can add results in the event processor corresponding to the ProgressChanged event, just as you access the ProgressPercentage attribute.
If multiple asynchronous operations are pending, you can use the UserState property to distinguish which operation is reporting incremental results.
If multiple asynchronous operations are suspended, you can use the UserState attribute to identify which operation is reporting incremental results.

 

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.