gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:40:58 25 4
gpt4 key购买 nike

我处于一个场景中,我需要通过 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com