{"id":28051,"date":"2019-11-13T00:00:00","date_gmt":"2019-11-12T23:00:00","guid":{"rendered":"https:\/\/blexin.com\/async-e-await-in-applicazioni-reali\/"},"modified":"2021-05-21T19:57:36","modified_gmt":"2021-05-21T17:57:36","slug":"async-and-await-in-real-applications","status":"publish","type":"post","link":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/","title":{"rendered":"Async and await in real applications"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"608\" data-attachment-id=\"28045\" data-permalink=\"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/attachment\/ebde7771-6bb2-4f29-9d23-c9e19c7af857-2\/\" data-orig-file=\"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&amp;ssl=1\" data-orig-size=\"1024,608\" data-comments-opened=\"0\" data-image-title=\"ebde7771-6bb2-4f29-9d23-c9e19c7af857\" data-image-description=\"\" data-image-caption=\"\" data-large-file=\"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&amp;ssl=1\" src=\"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?resize=1024%2C608&#038;ssl=1\" alt=\"\" class=\"wp-image-28045\" srcset=\"https:\/\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png 1024w, https:\/\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857-980x582.png 980w, https:\/\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857-480x285.png 480w\" sizes=\"auto, (min-width: 0px) and (max-width: 480px) 480px, (min-width: 481px) and (max-width: 980px) 980px, (min-width: 981px) 1024px, 100vw\" \/><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">When we use a method that needs a long time to run (i.e., for reading a large size file or downloading heavy resources from the network), in a synchronized application, the application itself stops running&nbsp;until the activity is completed. In these cases, the&nbsp;<strong>asynchronous<\/strong>&nbsp;programming is very helpful: it allows us to perform parallel execution of different tasks and wait for their completion&nbsp;if needed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">There are many different model types for this approach to programming:&nbsp;<strong>APM<\/strong>&nbsp;(Asynchronous Programming Model), the asynchronous model based on events (<strong>EAP<\/strong>), and the&nbsp;<strong>TAP<\/strong>, the asynchronous model based on tasks (<strong>Task<\/strong>). Let\u2019s see how we can implement the third method in C#, using the keywords async, and await.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One of the main problems of writing asynchronous code is&nbsp;maintainabilty: in fact, this programming method tends to complicate the code. Luckily, C#5 introduced a simplified approach, in which the compilator runs the difficult job, previously made by the developer, and the application preserves a logical structure, similar to the synchronous code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let\u2019s take an example. Suppose we have a .NET Core project, in which we should manage three entities: Area, Company, and Resource.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class Area\n{\n\u00a0\u00a0\u00a0\u00a0public int Id { get; set; }\n\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Required]\n\u00a0\u00a0\u00a0\u00a0&#x5B;StringLength(255)]\n\u00a0\u00a0\u00a0\u00a0public string Name { get; set; }\n}\n\u00a0\u00a0\npublic class Company\n{\n\u00a0\u00a0\u00a0\u00a0public int Id { get; set; }\n\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Required]\n\u00a0\u00a0\u00a0\u00a0&#x5B;StringLength(255)]\n\u00a0\u00a0\u00a0\u00a0public string Name { get; set; }\n}\n\u00a0\npublic class Resource\n{\n\u00a0\u00a0\u00a0\u00a0public int Id { get; set; }\n\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Required]\n\u00a0\u00a0\u00a0\u00a0&#x5B;StringLength(255)]\n\u00a0\u00a0\u00a0\u00a0public string Name { get; set; }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Now suppose we should save the values of these entities on a database using Entity Framework Core. The&nbsp;<strong>DbContext<\/strong>&nbsp;would be as:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class AppDbContext : DbContext\n{\n\u00a0\u00a0\u00a0\u00a0public DbSet&lt;Area&gt; Areas { get; set; }\n\u00a0\u00a0\u00a0\u00a0public DbSet&lt;Company&gt; Companies { get; set; }\n\u00a0\u00a0\u00a0\u00a0public DbSet&lt;Resource&gt; Resources { get; set; }\n\u00a0\u00a0\u00a0\u00a0public AppDbContext(DbContextOptions&lt;AppDbContext&gt; options) : base(options)\u00a0 {}\n\u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0override protected void OnModelCreating(ModelBuilder modelBuilder)\n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0modelBuilder.Entity&lt;Area&gt; ().HasData(\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 1, Name = &quot;Area1&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 2, Name = &quot;Area2&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 3, Name = &quot;Area3&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 4, Name = &quot;Area4&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 5, Name = &quot;Area5&quot;});\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0modelBuilder.Entity&lt;Company&gt; ().HasData(\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 1, Name = &quot;Company1&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 2, Name = &quot;Company2&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 3, Name = &quot;Company3&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 4, Name = &quot;Company4&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 5, Name = &quot;Company5&quot;});\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0modelBuilder.Entity&lt;Resource&gt;().HasData(\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 1, Name = &quot;Resource1&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 2, Name = &quot;Resource2&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 3, Name = &quot;Resource3&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 4, Name = &quot;Resource4&quot;},\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0new Area { Id = 5, Name = &quot;Resource5&quot;});\n\u00a0\u00a0\u00a0\u00a0}\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">As you can see from the code, we insert some sample data to work on. Suppose now we want to expose these data with a&nbsp;<em>Controller API<\/em>, both individually (for each entity), and with a method that joins them all, returning them&nbsp;with a single call.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With the synchronous approach, the&nbsp;<em>Controller API<\/em>&nbsp;would be:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;ApiController]\n&#x5B;Route(&quot;&#x5B;controller]&quot;)]\npublic class DataController : ControllerBase\n{\n\u00a0\u00a0\u00a0\u00a0private readonly AppDbContext db = null;\n\u00a0\u00a0\u00a0\u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0public DataController(AppDbContext db)\n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.db = db;\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\n\u00a0\u00a0\u00a0\u00a0public IActionResult Get()\n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var areas = this.GetAreas();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var companies = this.GetCompanies();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var resources = this.GetResources();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return Ok(new { areas = areas, companies = companies, resources = resources });\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Route(&quot;areas&quot;)]\n\u00a0\u00a0\u00a0\u00a0public Area&#x5B;] GetAreas() \n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return this.db.Areas.ToArray();\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Route(&quot;companies&quot;)]\n\u00a0\u00a0\u00a0\u00a0public Company&#x5B;] GetCompanies() \n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return this.db.Companies.ToArray();\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Route(&quot;resources&quot;)]\n\u00a0\u00a0\u00a0\u00a0public Resource&#x5B;] GetResources() \n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return this.db.Resources.ToArray();\n\u00a0\u00a0\u00a0\u00a0}\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The Get() method callS inside it the three methods&nbsp;that return single results, and it&nbsp;waits&nbsp;for the execution of each of them to be completed before it passes to the next. The three methods are not interrelated, then you don\u2019t need to wait for the execution of one of them in order to invoke another. You can then create three independent Tasks to parallelize the execution.<br>A first approach can be based on the method&nbsp;<strong>Run<\/strong>&nbsp;of the&nbsp;<strong>Task<\/strong>&nbsp;class&nbsp;that queues the specified job to be ran in the&nbsp;<em>thread-pool<\/em>&nbsp;and returns a&nbsp;<strong>Task<\/strong>&nbsp;object and it represents this job. In this way, methods are run at the same time on different threads of the pool:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic IActionResult Get()\n{\n\u00a0\u00a0\u00a0\u00a0var areas = Task.Run(() = &gt; this.GetAreas());\n\u00a0\u00a0\u00a0\u00a0var companies = Task.Run(() = &gt; this.GetCompanies());\n\u00a0\u00a0\u00a0\u00a0var resources = Task.Run(() = &gt; this.GetResources());\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 \n\u00a0\u00a0\u00a0\u00a0Task.WhenAll(areas, companies, resources);\n\u00a0\u00a0\u00a0\u00a0return Ok(new { areas = areas.Result, companies = companies.Result, resources = resources.Result });\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>Result<\/strong>&nbsp;property of&nbsp;<strong>Task<\/strong>&nbsp;contains the result of the elaboration. The method&nbsp;<em>WhenAll<\/em>&nbsp;permits to suspend the present thread execution&nbsp;until the completion of all Tasks. Running the code, we can note an interesting thing: the call interrupts, and it launches the following exception:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">AggregateException: One or more errors occurred. (A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see&nbsp;<a href=\"https:\/\/go.microsoft.com\/fwlink\/?linkid=2097913\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/go.microsoft.com\/fwlink\/?linkid=2097913&nbsp;<\/a>.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This error message tells us that methods are executed simultaneously on different threads, but an exception raises&nbsp;since they use the same instance as the&nbsp;<strong>DbContext&nbsp;<\/strong>for the connection to DB,<br>The&nbsp;<strong>DbContext<\/strong>&nbsp;class can\u2019t assure a&nbsp;<em>threadsafe<\/em>&nbsp;functioning: we can easily bypass this problem, avoiding that the&nbsp;<em>dependency injection<\/em>&nbsp;engine of .NET Core creates a single instance, and we create a separate instance for each method. As an example, let\u2019s see how the method GetAreas() would change:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic class DataController : ControllerBase\n{\n\u00a0\u00a0\u00a0\u00a0private readonly DbContextOptionsBuilder &lt;AppDbContext&gt; optionsBuilder = null;\n\u00a0\u00a0\u00a0\u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0public DataController(IConfiguration configuration)\n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0this.optionsBuilder = new DbContextOptionsBuilder &lt;AppDbContext&gt; ()\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0.UseSqlite(configuration.GetConnectionString(&quot;DefaultConnection&quot;));\n\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\n\u00a0\u00a0\u00a0\u00a0&#x5B;Route(&quot;areas&quot;)]\n\u00a0\u00a0\u00a0\u00a0public Area&#x5B;] GetAreas() \n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0using(var db = new AppDbContext(this.optionsBuilder.Options))\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return db.Areas.ToArray();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\u00a0\u00a0}\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Well, now it works. We should note that&nbsp;<em>Entity Framework Core<\/em>&nbsp;provides some methods to make asynchronous calls with the same&nbsp;<strong>DbContext<\/strong>, as the method&nbsp;<em>ToArrayAsync<\/em>, for example, which creates an array from an&nbsp;<em>IQueryable&lt;T&gt;<\/em>&nbsp; enumerating it asynchronously. This method returns a&nbsp;<strong>Task&lt;TSource[]&gt;<\/strong>, an activity that represents the asynchronous operation. In this way, we don\u2019t need to use&nbsp;<em>Task.Run()<\/em>&nbsp;anymore:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\npublic IActionResult Get()\n{\n\u00a0\u00a0\u00a0\u00a0var areas = this.GetAreas();\n\u00a0\u00a0\u00a0\u00a0var companies = this.GetCompanies();\n\u00a0\u00a0\u00a0\u00a0var resources = this.GetResources();\n\u00a0\u00a0\u00a0\u00a0Task.WhenAll(areas, companies, resources);\n\u00a0\u00a0\u00a0\u00a0return Ok(new { areas = areas.Result, companies = companies.Result, resources = resources.Result });\n}\n\u00a0\u00a0\n&#x5B;Route(&quot;areas&quot;)]\npublic Task&lt;Area&#x5B;]&gt; GetAreas() \n{\n\u00a0\u00a0\u00a0\u00a0return db.Areas.ToArrayAsync();\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Microsoft doesn\u2019t assure that these asynchronous methods work in every situation, anyway&nbsp;because the DbContext has not been designed to be threadsafe. You can consult this link for more information:&nbsp;<a href=\"https:\/\/docs.microsoft.com\/en-us\/ef\/core\/querying\/async\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/docs.microsoft.com\/en-us\/ef\/core\/querying\/async<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The best practice when you are working with Entity Framework Core is to have a DbContext for every asynchronous operation or waiting for each of them to be finished, before launching another one.<br>This best practice is ok when we have to make an asynchronous call and return the result. But what happens if we want to make some operations with the result&nbsp;before returning it? What if we want to add an element to the list? We should wait for results, add the element, and then return the modified list:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Route(&quot;companies&quot;)]\npublic Task&lt;Company&#x5B;]&gt; GetCompanies() \n{\n\u00a0\u00a0\u00a0\u00a0using (var db = new AppDbContext(this.optionsBuilder.Options))\n\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var data = this.db.Companies.ToListAsync().Result;\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0data.Insert(0, new Company() { Id = 0, Name = &quot;-&quot;});\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return data.ToArray();\n\u00a0\u00a0\u00a0\u00a0}\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Unfortunately, this code doesn\u2019t compile&nbsp;because the data.ToArray() returns an array and not a Task. In fact, we need three threads here: the main caller (Get()), the query on the database (this.db.Companies.ToListAsync()), and a thread, which adds one&nbsp;value to the list. We have three ways to do that: let\u2019s see them all with our three single methods. The first one, which we have already seen, can use the method Task.Run():<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Route(&quot;companies&quot;)]\npublic Task&lt;Company&#x5B;]&gt; GetCompanies()\n{\n\u00a0\u00a0\u00a0\u00a0\u00a0return Task.Run(() =&gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0using (var db = new AppDbContext(this.optionsBuilder.Options))\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var data = db.Companies.ToList();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0data.Insert(0, new Company() { Id = 0, Name = &quot;-&quot; });\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return data.ToArray();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0}\n\u00a0\u00a0\u00a0\u00a0\u00a0});\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">As an alternative, we can use the method&nbsp;<strong>ContinueWith()<\/strong>, that can be applied to the Tasks and in which we can specify a new Task to run, as soon as the previous one is finished:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Route(&quot;resources&quot;)]\npublic Task &lt;Resource&#x5B;]&gt; GetResources()\n{\n\u00a0\u00a0\u00a0\u00a0\u00a0using (var db = new AppDbContext(this.optionsBuilder.Options))\n\u00a0\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return db.Resources.ToListAsync()\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0.ContinueWith(dataTask = &gt;\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var data = dataTask.Result;\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0dataTask.Result.Insert(0, new Resource() { Id = 0, Name = &quot;-&quot; });\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return data.ToArray();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0});\n\u00a0\u00a0\u00a0\u00a0\u00a0}\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">We can get the compiler to do the \u201cdirty work\u201d and use the keywords&nbsp;<strong>async<\/strong>&nbsp;and&nbsp;<strong>await<\/strong>, that can create the Task for us:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\n&#x5B;Route(&quot;areas&quot;)]\npublic async Task &lt;Area&#x5B;]&gt; GetAreas()\n{\n\u00a0\u00a0\u00a0\u00a0\u00a0using (var db = new AppDbContext(this.optionsBuilder.Options))\n\u00a0\u00a0\u00a0\u00a0\u00a0{\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0var data = await db.Areas.ToListAsync();\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0data.Insert(0, new Area() { Id = 0, Name = &quot;-&quot; });\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0return data.ToArray();\n\u00a0\u00a0\u00a0\u00a0\u00a0}\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">As you can see in this last method, the code is much simpler and hides to us the creation of the Task, allowing us to give an asynchronous return. Let\u2019s imagine a scenario&nbsp;where calls are more than one, and how this approach makes everything more linear.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The side effect of our refactoring is that the method GetAreas() has become an&nbsp;<strong>asynchronous action<\/strong>. This fact means that when different requests arrive at this API, the thread of the pool allocated for the request will be released to be available for further requests until the DbContext terminate the data fetch.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I wish I intrigued you enough to analyze the argument in deep. The use of async and await is very convenient in many scenarios and, besides making the code much clean and linear, it can bring to an increment of application\u2019s general performances.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The code is available here:&nbsp;<a href=\"https:\/\/github.com\/fvastarella\/Programmazione-asincrona-con-async-await\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/github.com\/fvastarella\/Programmazione-asincrona-con-async-await<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">See you next!<\/p>\n\n\n\n\n","protected":false},"excerpt":{"rendered":"<p>Let\u2019s see how the keywords \u201casync\u201d and \u201cawait\u201d can simplify the multithreading programming in C# in real situations<\/p>\n","protected":false},"author":196716244,"featured_media":28045,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"off","_et_pb_old_content":"","_et_gb_content_width":"","_coblocks_attr":"","_coblocks_dimensions":"","_coblocks_responsive_height":"","_coblocks_accordion_ie_support":"","inline_featured_image":false,"jetpack_seo_llms_txt_always_include":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_wpcom_ai_launchpad_first_post":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"{title}\n\n{excerpt}\n\n{url}","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"_wpas_customize_per_network":false,"jetpack_post_was_ever_published":false},"categories":[688637524],"tags":[688637542,688637384],"class_list":["post-28051","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog-en","tag-dotnetcore-en","tag-c-en"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Async and await in real applications - Blexin<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Async and await in real applications - Blexin\" \/>\n<meta property=\"og:description\" content=\"Let\u2019s see how the keywords \u201casync\u201d and \u201cawait\u201d can simplify the multithreading programming in C# in real situations\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/\" \/>\n<meta property=\"og:site_name\" content=\"Blexin\" \/>\n<meta property=\"article:published_time\" content=\"2019-11-12T23:00:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-05-21T17:57:36+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/i1.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1\" \/>\n\t<meta property=\"og:image:width\" content=\"1024\" \/>\n\t<meta property=\"og:image:height\" content=\"608\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Francesco Vastarella\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Francesco Vastarella\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/\"},\"author\":{\"name\":\"Francesco Vastarella\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/#\\\/schema\\\/person\\\/388dae0ca9df603c88b5e41e29cf2d4d\"},\"headline\":\"Async and await in real applications\",\"datePublished\":\"2019-11-12T23:00:00+00:00\",\"dateModified\":\"2021-05-21T17:57:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/\"},\"wordCount\":1126,\"image\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/i0.wp.com\\\/blexin.com\\\/wp-content\\\/uploads\\\/2020\\\/12\\\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1\",\"keywords\":[\".NetCore\",\"C#\"],\"articleSection\":[\"Blog\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/\",\"url\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/\",\"name\":\"Async and await in real applications - Blexin\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/i0.wp.com\\\/blexin.com\\\/wp-content\\\/uploads\\\/2020\\\/12\\\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1\",\"datePublished\":\"2019-11-12T23:00:00+00:00\",\"dateModified\":\"2021-05-21T17:57:36+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/#\\\/schema\\\/person\\\/388dae0ca9df603c88b5e41e29cf2d4d\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#primaryimage\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/blexin.com\\\/wp-content\\\/uploads\\\/2020\\\/12\\\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/blexin.com\\\/wp-content\\\/uploads\\\/2020\\\/12\\\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1\",\"width\":1024,\"height\":608},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/blog-en\\\/async-and-await-in-real-applications\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/blexin.com\\\/en\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Async and await in real applications\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/#website\",\"url\":\"https:\\\/\\\/blexin.com\\\/en\\\/\",\"name\":\"Blexin\",\"description\":\"Con noi \u00e8 semplice\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/blexin.com\\\/en\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/blexin.com\\\/en\\\/#\\\/schema\\\/person\\\/388dae0ca9df603c88b5e41e29cf2d4d\",\"name\":\"Francesco Vastarella\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3b8deedae8f35372d5fba49f918006fb0a58a2943aff6ae52d3ff188e0c441bb?s=96&d=identicon&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3b8deedae8f35372d5fba49f918006fb0a58a2943aff6ae52d3ff188e0c441bb?s=96&d=identicon&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3b8deedae8f35372d5fba49f918006fb0a58a2943aff6ae52d3ff188e0c441bb?s=96&d=identicon&r=g\",\"caption\":\"Francesco Vastarella\"},\"url\":\"https:\\\/\\\/blexin.com\\\/en\\\/author\\\/francesco-vastarellablexin-com\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Async and await in real applications - Blexin","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/","og_locale":"en_US","og_type":"article","og_title":"Async and await in real applications - Blexin","og_description":"Let\u2019s see how the keywords \u201casync\u201d and \u201cawait\u201d can simplify the multithreading programming in C# in real situations","og_url":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/","og_site_name":"Blexin","article_published_time":"2019-11-12T23:00:00+00:00","article_modified_time":"2021-05-21T17:57:36+00:00","og_image":[{"width":1024,"height":608,"url":"https:\/\/i1.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1","type":"image\/png"}],"author":"Francesco Vastarella","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Francesco Vastarella","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#article","isPartOf":{"@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/"},"author":{"name":"Francesco Vastarella","@id":"https:\/\/blexin.com\/en\/#\/schema\/person\/388dae0ca9df603c88b5e41e29cf2d4d"},"headline":"Async and await in real applications","datePublished":"2019-11-12T23:00:00+00:00","dateModified":"2021-05-21T17:57:36+00:00","mainEntityOfPage":{"@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/"},"wordCount":1126,"image":{"@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1","keywords":[".NetCore","C#"],"articleSection":["Blog"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/","url":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/","name":"Async and await in real applications - Blexin","isPartOf":{"@id":"https:\/\/blexin.com\/en\/#website"},"primaryImageOfPage":{"@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#primaryimage"},"image":{"@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#primaryimage"},"thumbnailUrl":"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1","datePublished":"2019-11-12T23:00:00+00:00","dateModified":"2021-05-21T17:57:36+00:00","author":{"@id":"https:\/\/blexin.com\/en\/#\/schema\/person\/388dae0ca9df603c88b5e41e29cf2d4d"},"breadcrumb":{"@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#primaryimage","url":"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1","contentUrl":"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1","width":1024,"height":608},{"@type":"BreadcrumbList","@id":"https:\/\/blexin.com\/en\/blog-en\/async-and-await-in-real-applications\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blexin.com\/en\/"},{"@type":"ListItem","position":2,"name":"Async and await in real applications"}]},{"@type":"WebSite","@id":"https:\/\/blexin.com\/en\/#website","url":"https:\/\/blexin.com\/en\/","name":"Blexin","description":"Con noi \u00e8 semplice","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blexin.com\/en\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/blexin.com\/en\/#\/schema\/person\/388dae0ca9df603c88b5e41e29cf2d4d","name":"Francesco Vastarella","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/3b8deedae8f35372d5fba49f918006fb0a58a2943aff6ae52d3ff188e0c441bb?s=96&d=identicon&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/3b8deedae8f35372d5fba49f918006fb0a58a2943aff6ae52d3ff188e0c441bb?s=96&d=identicon&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/3b8deedae8f35372d5fba49f918006fb0a58a2943aff6ae52d3ff188e0c441bb?s=96&d=identicon&r=g","caption":"Francesco Vastarella"},"url":"https:\/\/blexin.com\/en\/author\/francesco-vastarellablexin-com\/"}]}},"jetpack_publicize_connections":[],"jetpack_likes_enabled":false,"jetpack_shortlink":"https:\/\/wp.me\/pcyUBx-7ir","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/i0.wp.com\/blexin.com\/wp-content\/uploads\/2020\/12\/ebde7771-6bb2-4f29-9d23-c9e19c7af857.png?fit=1024%2C608&ssl=1","_links":{"self":[{"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/posts\/28051","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/users\/196716244"}],"replies":[{"embeddable":true,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/comments?post=28051"}],"version-history":[{"count":7,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/posts\/28051\/revisions"}],"predecessor-version":[{"id":32924,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/posts\/28051\/revisions\/32924"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/media\/28045"}],"wp:attachment":[{"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/media?parent=28051"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/categories?post=28051"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blexin.com\/en\/wp-json\/wp\/v2\/tags?post=28051"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}