3 回答
TA贡献1815条经验 获得超6个赞
这是另一种方法。与svick和Ohad的答案类似的概念,但是对Process类型使用扩展方法。
扩展方式:
public static Task RunAsync(this Process process)
{
var tcs = new TaskCompletionSource<object>();
process.EnableRaisingEvents = true;
process.Exited += (s, e) => tcs.TrySetResult(null);
// not sure on best way to handle false being returned
if (!process.Start()) tcs.SetException(new Exception("Failed to start process."));
return tcs.Task;
}
包含方法中的示例用例:
public async Task ExecuteAsync(string executablePath)
{
using (var process = new Process())
{
// configure process
process.StartInfo.FileName = executablePath;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
// run process asynchronously
await process.RunAsync();
// do stuff with results
Console.WriteLine($"Process finished running at {process.ExitTime} with exit code {process.ExitCode}");
};// dispose process
}
- 3 回答
- 0 关注
- 549 浏览
添加回答
举报