简体   繁体   中英

Why does asynchronously running a process block the thread?

Based on this answer , I have the following ASP.NET Action that's supposed to run a process asynchronously. However, when I make multiple parallel requests, each runs only after the previous one completes. Why does this happen?

    public async Task<ActionResult> Index(string url)
    {
        var exePath = Server.MapPath("~/App_Data/dummy/bin/dummy.exe");
        var startInfo = new ProcessStartInfo
        {
            FileName = exePath,
            Arguments = url,
            UseShellExecute = false,
            CreateNoWindow = true,
            RedirectStandardInput = true,
            RedirectStandardOutput = true,
            RedirectStandardError = true
        };
        var process = new Process{ EnableRaisingEvents = true, StartInfo = startInfo};

        var tcs = new TaskCompletionSource<Process>();
        process.Exited += (sender, a) =>
        {
            tcs.SetResult(process);
        };
        process.Start();

        await tcs.Task;

        // todo: return process status/output
        return View();
    }

The code for dummy.exe , the process called in the MVC Action, is:

class Program
{
    static void Main(string[] args)
    {
        Thread.Sleep(5000);
        Console.WriteLine("Hello world!");
    }
}

There's probably two unrelated things going on here.

First, async doesn't do what you most likely think it does, at least in the context of a web application. The action cannot return a response until all work inside the action is complete. The fact that it's async doesn't make it return faster. Rather, it merely allows the the thread that is running the action to be returned to the pool while it's in a wait-state. However, even then, the thread must be truly waiting. Running a process is CPU-bound, so your async action here will essentially run synchronously always, because it needs the thread to run the process.

Second, you're most likely testing this in IIS Express, within Visual Studio. IIS Express is single-threaded, so that means all further requests will be blocked until the first completes. Therefore, unless you're running this in full IIS (which is multi-threaded) the requests will always be handled serially, regardless.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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