我处于一个场景中,我需要通过 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();
}
关于c# - 通过 WebAPI 异步调用进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431568/