Skip to main content
 首页 » 编程设计

c#之通过 WebAPI 异步调用进程

2024年01月29日24daizhj

我处于一个场景中,我需要通过 API 端点调用一个 exe 进程(即发即弃)。但是,我将调用的 exe 是一个长时间运行的 exe,但我需要等待它完成才能执行更多代码。这将在后台发生,客户不应该真正等待它。当我尝试下面的代码时,调用正在等待 exe 进程完成。我也试过使方法“异步”,但结果仍然相同。

    [HttpPost] 
    public async Task<bool> ToggleCarWeaverService(string command) 
    { 
        try 
        { 
            var fileName = @"SomeExe.exe"; 
            await _service.RunProcessAsync(command, fileName); 
            return true; 
 
        } 
        catch (Exception ex) 
        { 
            throw new HttpResponseException(HttpStatusCode.InternalServerError); 
        } 
    } 
 
 
    public Task<int> RunProcessAsync(string command, string fileName) 
    { 
        // Use ProcessStartInfo class 
        ProcessStartInfo startInfo = new ProcessStartInfo 
        { 
            CreateNoWindow = false, 
            UseShellExecute = true, 
            FileName = fileName, 
            WindowStyle = ProcessWindowStyle.Normal, 
            Arguments = command 
        }; 
 
        try 
        { 
            var tcs = new TaskCompletionSource<int>(); 
 
            var process = new Process 
            { 
                StartInfo = startInfo, 
                EnableRaisingEvents = true 
            }; 
 
            process.Exited += (sender, args) => 
            { 
                tcs.SetResult(process.ExitCode); 
                //Do more code 
                process.Dispose(); 
 
            }; 
 
            process.Start(); 
 
            return tcs.Task; 
        } 
        catch (Exception ex) 
        { 
            // Log error. 
            throw ex; 
        } 
    } 

请您参考如下方法:

不要等待异步任务。

使用Task.Run包装并继续

[HttpPost] 
public IHttpActionResult ToggleCarWeaverService(string command) { 
    Task.Run(async () => { 
        var fileName = @"SomeExe.exe"; 
        await _service.RunProcessAsync(command, fileName); 
        //...other code after process finish 
    }); 
    return Ok(); 
}