国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Event-basedAsynchronousPatternOverview基于事件的異步模式概覽

2019-11-14 16:02:00
字體:
來源:轉載
供稿:網友

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

applications that perform many tasks simultaneously, yet remain responsive to user interaction, often require a design that uses multiple threads.
同時執行多項任務,并且仍要相應用戶交互的應用,通常需要一個使用多線程的設計。
The System.Threading namespace PRovides all the tools necessary to create high-performance multithreaded applications,
System.Threading命名空間提供了所有必要的工具來創建高效的多線程應用
but using these tools effectively requires significant experience with multithreaded software engineering.
但是有效的使用這些工具需要有豐富的使用多線程軟件工程的經驗
For relatively simple multithreaded applications, the BackgroundWorker component provides a straightforward solution.
相較而言,簡單的多線程應用,BackgroundWorker組件提供一個簡單的解決方案
For more sophisticated asynchronous applications, consider implementing a class that adheres to the Event-based Asynchronous Pattern.
對于更復雜的亦不應用,可以考慮實現一個支持基于事件的異步模式的類

The Event-based Asynchronous Pattern makes available the advantages of multithreaded applications while hiding many of the complex issues inherent in multithreaded design. Using a class that supports this pattern can allow you to:
基于事件的一步模式,利用了多線程應用的優點,同時隱藏了多線程設計中固有的復雜問題,使用支持此模式的類,可以確保你:
1.Perform time-consuming tasks, such as downloads and database Operations, "in the background," without interrupting your application.
在后臺執行耗時的任務,比如下載或者數據庫操作,但是不會中斷你的應用
2.Execute multiple operations simultaneously, receiving notifications when each completes.
同時執行多個操作,當每一個操作都完成的時候,接收通知
3.Wait for resources to become available without stopping ("hanging") your application.
等待資源可用,而且不會停止你的應用
4.Communicate with pending asynchronous operations using the familiar events-and-delegates model.
使用熟悉的事件委托模式,來和掛起的異步操作通訊

 

A class that supports the Event-based Asynchronous Pattern will have one or more methods named MethodNameAsync.
一個支持基于事件的異步模式的類,會有一個或多個方法,按照方法名+后綴Async的規則來命名。
These methods may mirror synchronous versions, which perform 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.
這個類也許還有方法名+Completed后綴的事件,也許有方法名+AsyncCancel后綴的方法(或者直接就是CancelAsync)。

 

PictureBox is a typical component that supports the Event-based Asynchronous Pattern.
PictureBox就是一個支持基于事件的異步模式的典型組件。
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.
你可以調用Load方法來同步下載一張圖片,但是如果圖片太大的話或者網速太慢的話,你的應用將會停止響應(或掛起),直到下載操作完成并且調用Load方法返回。

 

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 would handle any other event.
如果你想要你的應用邊運行邊下載圖片,你可以調用LoadAsync方法并處理LoadCompleted事件
When you call the LoadAsync method, your application will continue to run while the download proceeds on a separate thread ("in the background").
當你調用LoadAsync方法的時候,你的應用可以繼續運行,而下載將會在一個獨立的線程上開始(后臺)
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.
你的事件處理器將會在圖片下載操作完成的時候被調用,事件處理器可以通過檢查AsyncCompletedEventArgs參數來判斷下載是否成功完成。

 

The Event-based Asynchronous Pattern requires that an asynchronous operation can be canceled, and the PictureBox control supports this requirement with its CancelAsync method.
基于事件的異步模式需要保證一個異步操作可以被取消,PictureBox控件通過它的CancelAsync方法來支持這個要求。
Calling CancelAsync submits a request to stop the pending download, and when the task is canceled, the LoadCompleted event is raised.
調用CancelAsync提交一個請求來停止下載操作,當任務被取消的時候,將會觸發LoadCompleted事件

 

注意:
It is possible that the download will finish just as the CancelAsync request is made, so Cancelled may not reflect the request to cancel.
有一種可能,下載會在你剛調用了CancelAsync的時候完成,導致事件參數中的Cancelled可能無法反映取消的
This is called a race condition and is a common issue in multithreaded programming.
這種現象被稱為爭用條件,這是多線程編程中很常見的一個問題

 

 

Characteristics of the Event-based AsyncChronous Pattern基于事件的一步模式的特征
The Event-based Asynchronous Pattern may take several forms, depending on the complexity of the operations supported by a particular class.
基于事件的異步模式可能有多種表現形式,這取決于特定類所支持的操作的復雜程序
The simplest classes may have a single MethodNameAsync method and a corresponding MethodNameCompleted event.
最簡單類只有一個MethodNameAsync方法以及一個對應的MethodNameCompleted事件
More complex classes may have several MethodNameAsync methods, each with a corresponding MethodNameCompleted event, as well as synchronous versions of these methods.
更復雜的類會有多個MethodNameAsync方法,并且每個方法都有對應的MethodNameCompleted事件,除此之外,這些異步方法還有對應的同步方法。
Classes can optionally support cancellation, progress reporting, and incremental results for each asynchronous method.


An asynchronous method may also support multiple pending calls (multiple concurrent invocations), allowing your code to call it any number of times before it completes other pending operations.
異步方法可能支持多個掛起調用(多個并發的調用),允許你在它完成其他掛起操作之前調用此方法任意多次。
Correctly handling this situation may require your application to track the completion of each operation.
為了處理這種情況,這就要求你的應用可以追蹤每一個操作的完成進度

 

  • 1.Examples of the Event-based AsyncChronous Pattern基于事件的異步模式的例子

The SoundPlayer and PictureBox components represent simple implementations of the Event-based Asynchronous Pattern.
SoundPlayer組件以及PictureBox組件,代表了基于事件的異步模式的簡單實現。
The WebClient and BackgroundWorker components represent more complex implementations of the Event-based Asynchronous Pattern.
WebClient組件以及BackgroundWorker組件,代表了基于事件的一步模式的更復雜的實現
Below is an example class declaration that conforms to the 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. 
虛構的AsyncExample類有2個方法,它們都支持同步和異步調用
The synchronous overloads behave like any method call and execute the operation on the calling thread;
同步重載就像其他任何方法調用一樣在調用的線程上來執行操作
if the operation is time-consuming, there may be a noticeable delay before the call 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."
異步重載將會在另外一個線程上執行操作并立即返回,當操作在后臺執行的時候,允許調用線程繼續執行。

 

  • 2.AsyncChronous Method Overloads異步方法的重載

There are potentially two overloads for the asynchronous operations: single-invocation and multiple-invocation.
對異步操作而言,有2個潛在的重載:單次調用以及多次調用
You can distinguish these two forms by their method signatures: the multiple-invocation form has an extra parameter called userState.
你可以通過它們的方法簽名來區分這2種形式,多次調用的形式有一個叫做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.
多次調用的形式確保了如下操作變得可能:讓你的代碼可以多次調用Method1Async(string param, object userState)方法多次而無需等待掛起的異步操作結束
If, on the other hand, you try to call Method1Async(string param) before a previous invocation has completed, the method raises an InvalidOperationException.
另一方面,如果你在之前的調用還沒有結束前,嘗試再次調用Method1Async(string param)這個同步方法的時候,這個同步方法將會觸發一個無效操作的異常

The userState parameter for the multiple-invocation overloads allows you to distinguish among asynchronous operations.
多次調用的重載參數userState允許你區分不同的異步操作
You provide a unique value (for example, a GUID or hash code) for each call to Method1Async(string param, object userState),
你可以在每一次調用Method1Async(string param, object userState)方法時,使用一個獨一無二的值傳遞給此方法(比如GUID或哈希碼)
and when each operation is completed, your event handler can determine which instance of the operation raised the completion event.
當每次操作完成的時候,你的事件處理器可以依據這個獨一無二的值來判斷哪一個操作實例觸發了完成事件

 

  • 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.
如果你使用多次調用的重載,你的代碼需要通過userState對象(任務編號)來追蹤掛起的任務
For each call to Method1Async(string param, object userState), you will typically generate a new, unique userState object and add it to a collection.
每一次調用Method1Async(string param, object userState)方法時,你通常需要生成一個新的,獨一無二的userState對象,并將它加入到一個結合中。
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.
當和這個userState對象符合的任務觸發了完成事件時,你的完成方法實現,需要檢查AsyncCompletedEventArgs.UserState,并且將它從集合中移除。
Used this way, the userState parameter takes the role of a task ID.
通過這種方法,userState參數扮演了任務編號的角色

注意:
You must be careful to provide a unique value for userState in your calls to multiple-invocation overloads.
在你調用多次調用重載的時候,你必須足夠小心來為userState提供一個獨一無二的值。
Non-unique task IDs will cause the asynchronous class throw an ArgumentException.
如果任務編號不是獨一無二的話,將會導致異步類拋出一個參數錯誤的異常

 

  • 4.Canceling Pending Operations取消掛起的操作

It is important to be able to cancel asynchronous operations at any time before their completion.
在異步操作完成之前,要確保可以隨時取消異步操作,這很重要。
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).
實現了基于事件的異步模式的類,會有一個CancelAsync方法(如果僅有一個異步方法的話)或者有一個MethodNameAsyncCancel方法(如果有多個異步方法的話)

Methods that allow multiple invocations take a userState parameter, which can be used to track the lifetime of each task.
帶有userState參數的多次方法調用,可以用來追蹤每個任務的生命周期
CancelAsync takes a userState parameter, which allows you to cancel particular pending tasks.
CancelAsync方法有一個userState參數,確保你可以取消指定的掛起的任務

Methods that support only a single pending operation at a time, like Method1Async(string param), are not cancelable.
一次僅支持一個單獨的掛起操作方法,就像Method1Async(string param)一樣,是不可以取消的

 

  • 5.Receiving 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.
符合基于事件的異步模式的類為了跟蹤進度和增量結果,會提供事件。
This will typically be named ProgressChanged or MethodNameProgressChanged, and its corresponding event handler will take a ProgressChangedEventArgs parameter.
事件通常被命名為ProgressChanged或MethodNameProgressChanged,并且會有一個和事件處理器相對應的ProgressChangedEventArgs事件參數

The event handler for the ProgressChangedevent can examine the ProgressChangedEventArgs.ProgressPercentage property to determine what percentage of an asynchronous task has been completed.
ProgressChangedevent的事件處理器可以通過ProgressChangedEventArgs.ProgressPercentage屬性來檢查異步任務完成的百分比
This property will range from 0 to 100, and it can be used to update the Value property of a ProgressBar.
此屬性的范圍從0到100,它可以用來更新進度條的Value屬性
If multiple asynchronous operations are pending, you can use the ProgressChangedEventArgs.UserState property to distinguish which operation is reporting progress.
如果多個異步操作掛起,你可以通過ProgressChangedEventArgs.UserState屬性來區分是哪一個操作在報告進度。

Some classes may report incremental results as asynchronous operations proceed.
有些類可以在異步操作進行的同時,報告增量結果
These results will be stored in a class that derives from ProgressChangedEventArgs and they will appear as properties in the derived class.
結果被保存在一個從ProgressChangedEventArgs派生的類中,增量結果作為派生類的屬性出現
You can access these results in the event handler for the ProgressChanged event, just as you would access the ProgressPercentage property.
你可以在ProgressChanged事件對應的事件處理器中訪問增加結果,就像你訪問ProgressPercentage屬性一樣
If multiple asynchronous operations are pending, you can use the UserState property to distinguish which operation is reporting incremental results.
如果有多個異步操作掛起,你可以通過UserState屬性來區分哪一個操作正在報告增量結果

 


上一篇:獲取mac地址

下一篇:.net鍵盤

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 全椒县| 通许县| 桐庐县| 稷山县| 贵阳市| 阜阳市| 汉寿县| 泸溪县| 咸阳市| 富锦市| 和平县| 河西区| 神农架林区| 兴业县| 饶河县| 若尔盖县| 岫岩| 富裕县| 南昌市| 益阳市| 珠海市| 休宁县| 昌黎县| 山东省| 界首市| 绥棱县| 子洲县| 贞丰县| 探索| 通江县| 青阳县| 广南县| 交城县| 合山市| 伊宁市| 连云港市| 茂名市| 英德市| 三门县| 逊克县| 宝应县|