. Net frameworks5.0 is mainly engaged in asynchronous programming APM. It is not a new thing in fact, but a Microsoft encapsulation of concepts such as the previous thread, proposing keywords such as await and async, the Task class is referenced, which greatly simplifies the development of APM. Next we will introduce the application of APM through a specific example.
Instance description
There is a WEB-oriented API interface that is required in our project. The main function of this API is to send notifications to other projects. If a user clicks a reply post, A notification may be generated along with the PHP end, and this notification may need to be reflected. In this way, cross-network and cross-platform interface APIs will emerge. During communication, the network is uncontrollable and its response speed is unpredictable. Therefore, this notification function should be implemented using asynchronous programming (APM, not XMLHTTPRequest ).
Knowledge Point
Asynchronous Method: Provides a simple way to complete the work that may take a long time to run without stopping the caller's thread. The caller of the asynchronous method can continue to work without waiting for the completion of the Asynchronous Method.
Await: The operator is applied to the task suspension method of An Asynchronous Method until the task is completed. Task indicates a job in progress.The await expression does not block the thread on which it executes.
Async: The async modifier indicates the method. It modifies the lambda expression or the anonymous method asynchronously.
Task class: It indicates a Task, which is supported in. net4.5 and belongs to the namespace System. Threading. Tasks. You can use the Task class to conveniently start a new thread.
Code display
Asynchronous code:
/// <Summary> /// Asynchronous Method, solve the long wait problem // </summary> /// <param name = "action"> </param> // <param name = "entity"> </param >/// <returns> </returns> public async Task <VMessage> AsyncAdd (Func <FAQ_Info, VMessage> fun, FAQ_Info entity) {return await System. threading. tasks. task. run () =>{ return fun (entity );});}
Call code:
var repository = new NoticeInfoService(); repository.AsyncAdd((a) => { return repository.TeacherReplyFAQ(a); }, faqInfo);
TIPS: the Func delegate is used to unify some types of implementations, which reduces the amount of repeated code.