The implementation of Async/Await in ASP.NET Core Controller Actions is not functioning as intended

Hello, I've encountered an issue with the code in my controller:

[HttpGet]
[Route("/Test")]
public async Task<IActionResult> Test() {
    Console.WriteLine("foo");
    await Task.Delay(2000);
    Console.WriteLine("bar");
    return Ok();
}

I attempted to test it using JavaScript:

for(let i=0; i<2; i++){
    axios.get('/Test').then(response => {
        console.log(`task ${i} finish`)
    })  
}

The expected server output should be:

foo
foo
foo
bar
bar
bar

However, what I actually received was:

foo
bar
foo
bar
foo
bar

I'm confused as to why await Task.Delay(2000) did not allow the control flow to handle other requests concurrently. It seems like the action method is not capable of handling a large number of requests simultaneously. Am I misunderstanding something about async/await? What changes should I make if I want to simulate a non-blocking lengthy web service call?

I've read this post but still can't find a solution

Answer №1

ASP.NET typically processes requests from the same client in sequential order, meaning it won't start processing a second request until the first one is finished. This was common in older versions of ASP.NET MVC on the full framework to prevent concurrent access to session state. If needed, this behavior could be changed by using the

SessionState(SessionStateBehaviour.Disabled)
attribute. For more information, you can refer to this question on Stack Overflow: ASP.NET MVC and Ajax, concurrent requests?. Similar principles may apply to ASP.NET Core.

Am I misunderstanding something about async/await? What should I implement if I want to simulate a non-blocking lengthy web service call?

Although request processing isn't blocking, it does occur sequentially. However, accessing the same action from different clients (browsers) will show that they are executed in parallel.

Answer №2

Although I haven't had much experience with axios before, it seems like the issue lies in your javascript code rather than your ASP.NET code.

ASP.NET handles async/await operations smoothly, and your example seems to be correctly utilizing them. The problem arises from the fact that your javascript makes one request at a time, waits for the response (which takes 2 seconds), and then proceeds with the for loop.

for(let i=0; i<2; i++){
    // This initiates a request to /Test and awaits the response
    // Since your controller pauses for 2 seconds before returning a success status
    // It appears synchronous
    axios.get('/Test').then(response => {
        console.log(`task ${i} complete`)
    })  
}

Have you considered using a callback-based function for your tests instead?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fixing extended properties on an express request can be done by following these steps

I've been working on a JavaScript middleware where I can extract user information using the "req" object in the route handler. When I log currentUser, I get the expected value, but I'm encountering a TypeScript error warning: Property 'curre ...

Create an animated A-frame box that moves randomly within a designated space

Looking to add some movement to my A-frame scene with a random box animation. I want to utilize the animation property to make an entity move randomly within a specified area. The goal is to have a box animate to a random position within coordinates rang ...

What is the best way to secure a folder and its contents utilizing sessions for added protection?

Currently, I am developing a project that involves assigning each user a dedicated folder for uploading files. However, there is a security concern where any user could potentially access files by simply typing in the path and filename. I am exploring met ...

The image fails to display correctly

As I work on creating a basic webpage in HTML and JavaScript, my goal is to validate certain parameters (such as width, height) of an image that users upload via a form. In JavaScript, I extract the file from the form and attempt to display it as an image ...

Sending Ajax requests to web services hosted on a dual-node NLB

I am currently managing a two-node NLB configuration where multiple web services need to be accessed from the client-side using ajax POST requests. When visiting the page at: http://clusternode1/ everything works smoothly. Similarly, when accessing it f ...

Ways to set a timeout for a hyperlink?

I have implemented two functions on the same element. One is AJAX for saving an image and the other is prettyPhoto ajax for displaying that image. Here is an example: This is the event > <a rel="prettyPhoto[ajax]" onClick="return false" > onMous ...

Fluctuating issues with deserialization in REST WCF Service on Windows Communication Foundation in .NET version 4.5

After upgrading our project to Visual Studio 2012 and targeting the .NET framework 4.5 instead of 4.0, we have been encountering intermittent serialization exception issues when trying to return data from our service methods. To debug the problem, we have ...

Utilizing Parallax.js within the React Framework

Just starting out with React and attempting to integrate the Parallax.js library into my project. I've completed the installation using npm, imported the library, and followed this helpful discussion related to my query. However, I'm encounterin ...

What is the best way to create a deep clone of an XMLDocument Object using Javascript?

I am currently working on a project that involves parsing an XML file into an XMLDocument object using the browser's implementation of an XML parser, like this: new DOMParser().parseFromString(text,"text/xml"); However, I have encountered a situatio ...

Refresh WebPage automatically after a Servlet successfully uploads and processes an image

I have a webpage that includes an image and a button. When the button is clicked, it uploads the image by submitting a form to a file upload servlet. However, after successfully uploading the image, the servlet does not display it in the img tag. Here is ...

Completely digital Mongoose schema that resides solely in memory and is not saved permanently

Having trouble locating any documentation or references on this topic, which could suggest that I am approaching it incorrectly. Is there a way to utilize a Mongoose schema that is completely virtual, meaning it is not stored in the database? I have vari ...

Express Route Handler doesn't work for specific file types

I am currently working on setting up a route handler for requests to '.js' files. I have successfully configured middleware to serve static files from a "/dist" directory, which is functioning correctly. However, I am facing an issue where the r ...

Having trouble executing the npm start command for ReactJS

Below is the code snippet from my file named server.js if(process.env.NODE_ENV !== 'production') { require('dotenv').parse() } const express = require('express') const app = express() const expressLayouts = require(' ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Switching the parent to child component value in Vue.js to show or hide elements using v-show within a v-for loop

I'm attempting to display a list of items in a v-for and toggle their visibility individually. Initially, I had all the code in one component which caused every element in the loop to open when the button was clicked: <template> <div v-for ...

Error encountered in React Material UI: Appbar - TypeError occurred when attempting to read properties that are undefined (specifically, reading '100')

Currently, I am working on developing a multi-step form using Material UI components. However, upon importing the necessary components, an error is being displayed in my code snippet: import React from 'react'; import { ThemeProvider } from &a ...

The Alertify dialog vanished without being able to confirm

While working on some code, I encountered a specific issue: alertify.dialog("confirm").set( { 'labels': { ok: 'Personal', cancel: 'Share' }, 'message': 'Select target:', ...

Identifying the opening of a folder or file in an electron/node application

Is there a way to retrieve the name of a folder or file when they are opened? I have tried using fs.watch event, but it only seems to work when renaming, adding, or removing files/folders within the specified directory. For instance: //This code only de ...

`How can you effectively simulate class modules in Jest?`

Working with the amplitude module requires me to start by creating an instance of a class and then use its methods. Here's the initial code snippet: var Amplitude = require('amplitude'); const amplitude = new Amplitude(process.env.amplitude ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...