Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for The Power of Asynchronous Code in your web API
Oscar Montenegro
Oscar Montenegro

Posted on • Originally published atunitcoding.com

     

The Power of Asynchronous Code in your web API

Hello my fellow developers, on the last article I showed youhow to add data validation using the fluent validation Nuget package. We discussed the relevance of implementing data validation for our API and for many other kinds of projects and also we saw how easy it was to implement yet the benefits are huge.

Today I will teach you how you can implement asynchronous code for your web API, you will see how easy it is and how you will leverage the power of asynchronous code for your app. But before we can start coding we need to understand what is asynchronous programming and what uses it have. So without further ado let’s get into today’s article.

What is asynchronous programming?

Software development has two primary paradigms when it comes to handling tasks: synchronous and asynchronous programming. Synchronous programming executes tasks one after the other, in a predetermined order. On the other hand, asynchronous programming enables the execution of multiple tasks simultaneously, without waiting for the previous task to finish. This article will dive deeper into asynchronous programming, its importance, and its various uses.

Why is Asynchronous Programming Important?

Asynchronous programming is essential for improving the performance and responsiveness of software applications. It is particularly useful for applications that require heavy data processing or network communication. By allowing multiple tasks to execute simultaneously, applications can run more efficiently and effectively. It is beneficial because it eliminates the need to wait for each task to complete before moving on to the next one.

Another advantage of asynchronous programming is its ability to handle long-running tasks without blocking the application's main thread. When a task takes a long time to complete, synchronous programming can cause the application to become unresponsive or even crash. Asynchronous programming enables applications to keep functioning normally while long-running tasks are processed in the background, thereby improving the overall user experience.

What Uses Does Asynchronous Programming Have?

Asynchronous programming has a wide range of uses in software development. One of its primary uses is in web development, where it handles requests and responses from servers. By using asynchronous programming, web applications can process multiple requests simultaneously, improving the overall performance and user experience.

Mobile app development is another area where asynchronous programming is commonly used. It handles tasks such as data synchronization, database access, and network communication. As a result, mobile apps can continue to function smoothly and responsively even when performing complex tasks in the background.

Asynchronous programming is also useful in gaming, artificial intelligence, and machine learning. These applications require the processing of multiple tasks simultaneously, which can be achieved through asynchronous programming. It helps to improve the performance and efficiency of these applications, leading to better overall results.

Clone the repo on GitHub

Before starting if you want to follow along with this tutorial you can clone the GitHub repository and make sure you get the code from theFluentValidation branch which contains the latest code changes up to this point.

GitHub - Osempu/BlogAPI at FluentValidation

Update the IPostRepository interface

We need to update the post repository class to access the database asynchronously but before we can do that we actually need to update theIPostRepository interface as it defines the contract the repository class needs to comply.

publicinterfaceIPostRepository{Task<IEnumerable<Post>>GetPostAsync();Task<Post>GetPostAsync(intid);TaskAddAsync(Postpost);TaskEditAsync(Postpost);TaskDeleteAsync(intid);}
Enter fullscreen modeExit fullscreen mode

We need to return aTask<T> so for theGet methods we will wrap the return type inside a task and for theAdd,Edit, andDelete we will simply return a Task as we cannot return void on an async method and also we will update the name of every function as they will now work asynchronously we will append theAsync word.

Update PostRepository class 🏦

Now we should be getting an error because we changes the return type for every method defined in theIPostRepository interface so we need to update ourPostRepository as well to make sure we comply with what our interface states.

publicclassPostRepository:IPostRepository{privatereadonlyBlogDbContextcontext;publicPostRepository(BlogDbContextcontext){this.context=context;}publicasyncTaskAddAsync(Postpost){context.Add(post);awaitcontext.SaveChangesAsync();}publicasyncTaskDeleteAsync(intid){varpost=context.Posts.Find(id);context.Remove(post);awaitcontext.SaveChangesAsync();}publicasyncTaskEditAsync(Postpost){context.Entry(post).State=EntityState.Modified;awaitcontext.SaveChangesAsync();}publicasyncTask<IEnumerable<Post>>GetPostAsync(){varallPosts=awaitcontext.Posts.ToListAsync();returnallPosts;}publicasyncTask<Post>GetPostAsync(intid){varpost=awaitcontext.Posts.FindAsync(id);returnpost;}}
Enter fullscreen modeExit fullscreen mode

Let’s begin by changing the names of all the methods and append theAsync word as they will now be working asynchronously, then add the async keyword and change the return type for every method to fully comply with the method signature defined by our interface.

Now the last step is to callSaveChangesAsync method in ourAdd,Edit, andDelete methods. For theGet method that retrieves all the posts we need to change theToList() toToListAsync and that would be enough, we need to do the same for the Get method that retrieves a single post but instead of usingToListAsync we will replace theFind method for its async versionFindAsync and there you go now the repository class is calling the database asynchronously.

Making the Post Controller Async 🎮

Now all that is left is to update our controller endpoints to make them work asynchronously.

**[HttpGet]publicasyncTask<IActionResult>GetPost(){varposts=awaitrepository.GetPostAsync();varpostsDto=mapper.Map<IEnumerable<PostResponseDTO>>(posts);logger.LogDebug($"Get method called, got{postsDto.Count()} results");returnOk(postsDto);}[HttpGet("{id:int}")]publicasyncTask<IActionResult>GetPost(intid){try{varpost=awaitrepository.GetPostAsync(id);varpostDto=mapper.Map<PostResponseDTO>(post);returnOk(postDto);}catch(Exceptionex){logger.LogError(ex,$"Error getting post with id{id}");throw;}}[HttpPost]publicasyncTask<IActionResult>CreatePost(AddPostDTOaddPostDTO){try{if(!ModelState.IsValid){returnBadRequest();}varnewPost=mapper.Map<AddPostDTO,Post>(addPostDTO);newPost.CreatedDate=DateTime.Now;awaitrepository.AddAsync(newPost);returnCreatedAtAction(nameof(GetPost),new{id=newPost.Id},null);}catch(Exceptionex){logger.LogError(ex,"Unexpected error on Post method");throw;}}[HttpPut]publicasyncTask<IActionResult>EditPost([FromBody]EditPostDTOeditPostDto){try{if(!ModelState.IsValid){returnBadRequest();}varpost=mapper.Map<EditPostDTO,Post>(editPostDto);post.LastUpdated=DateTime.Now;awaitrepository.EditAsync(post);returnNoContent();}catch(Exceptionex){logger.LogError(ex,"Unexpected error on Put(Edit) Method");throw;}}[HttpDelete("{id:int}")]publicasyncTask<IActionResult>DeletePost(intid){try{awaitrepository.DeleteAsync(id);returnNoContent();}catch(Exceptionex){logger.LogError(ex,$"Unexpected error on Delete method trying to delete post with Id{id}");throw;}}**
Enter fullscreen modeExit fullscreen mode

Here what we did is that in every endpoint we added theasync keyword and set the return type toTask<IActionResult>. Also, we now call the async version of the repository methodsAddAsync,EditAsync,DeleteAsync, andGetAsync.

Test the API 🧪

Now you can proceed to test the API, you will notice no change as it will run as before but now behind the scenes, it can take requests asynchronously and also the interaction with the database is asynchronous.

Conclusion 🌇

Asynchronous programming is an essential paradigm in software development, providing a wide range of uses and benefits. It enables the execution of multiple tasks simultaneously, leading to more efficient and effective software applications. It also enables long-running tasks to be processed without blocking the main thread, improving the overall user experience. As such, it is a critical tool for developers looking to create high-performance software applications. By embracing asynchronous programming, developers can create faster, more efficient, and more responsive applications, leading to better overall user experiences.

As always thanks for reading and considering supporting me on my blogUnit Coding and on my youtube channel under the same nameUnit Coding. Keep posted for my future articles on web API development and also for cool projects using ASP NET Core.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I'm a passionate software engineer that loves to build projects from scratch and to be continuously learning something new to apply it to real-world projects!
  • Location
    Mexico
  • Joined

More fromOscar Montenegro

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp