Like the title suggests, is there an equivalent to Process.Start
(allows you run another application or batch file) that I can await?
I'm playing with a small console app and this seemed like the perfect place to be using async and await but I can't find any documentation for this scenario.
What I'm thinking is something along these lines:
void async RunCommand()
{
var result = await Process.RunAsync("command to run");
}
Process.Start()
only starts the process, it doesn't wait until it finishes, so it doesn't make much sense to make it async
. If you still want to do it, you can do something like await Task.Run(() => Process.Start(fileName))
.
But, if you want to asynchronously wait for the process to finish, you can use the Exited
event together with TaskCompletionSource
:
static Task<int> RunProcessAsync(string fileName)
{
var tcs = new TaskCompletionSource<int>();
var process = new Process
{
StartInfo = { FileName = fileName },
EnableRaisingEvents = true
};
process.Exited += (sender, args) =>
{
tcs.SetResult(process.ExitCode);
process.Dispose();
};
process.Start();
return tcs.Task;
}