简体   繁体   English

使我的 MVC Async controller 方法异步,以便它们可以同时处理

[英]Making my MVC Async controller methods asynchronous so they can process at the same time

I have the following async code:我有以下异步代码:

public class AsynchronousController : AsyncController
{
    public ActionResult IndexSynchronous(string city)
    {
        return View("Index");
    }

    public async Task<ActionResult> AsyncTest(string call1, string call2)
    {
        await Task.Delay(10000);
        return null;
    }
}

The goal is that I can simply open IndexSynchronous while AsyncTest is processing, but this way it does not work.目标是我可以在 AsyncTest 正在处理时简单地打开 IndexSynchronous,但这样它不起作用。 I verified this by first calling Asynctest and then calling IndexSynchronous, which is still waiting for the other action.我通过首先调用 Asynctest 然后调用 IndexSynchronous 来验证这一点,它仍在等待其他操作。

Could anyone tell me what I am missing?谁能告诉我我错过了什么?

Async - Await is not about parallel programming. Async - Await 与并行编程无关。 It is meant to avoid useless CPU processing while waiting for IO operations.这是为了避免在等待 IO 操作时进行无用的 CPU 处理。

When you do:当你这样做时:

string fileContent = await GetFileContent();

you're just telling the current thread to stop its execution until it receives an interupt (IO operation completed).您只是告诉当前线程停止执行,直到它收到中断(IO 操作完成)。 Now tasks come in: when a thread which is executing a tasks awaits an IO operation to continue it can start executing another task while its waiting.现在任务进来了:当正在执行任务的线程等待IO 操作继续时,它可以在等待时开始执行另一个任务。

The degree of parallelism of a process is given by the number of thread of the threadpool that is using.进程的并行度由正在使用的线程池的线程数给出。 Each thread than executes tasks.每个线程都比执行任务。 When a thread calls awaits stop the execution of the current task and starts executing another one.当一个线程调用 await 时,会停止当前任务的执行并开始执行另一个任务。

Async - Await is about improving performance by avoiding thread to use CPU while waiting for IO operation Async - Await是关于通过避免线程在等待 IO 操作时使用 CPU 来提高性能

To answer your question, even in old ASP.NET web applications without async controllers you are able to process different requests (and so different controller actions) at the same time.要回答您的问题,即使在没有异步控制器的旧 ASP.NET web 应用程序中,您也可以同时处理不同的请求(以及不同的 controller 操作)。 You don't have to do anything to reach this.你不需要做任何事情来达到这个目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM