是否有与 Process.Start 等效的异步? [英] Is there any async equivalent of Process.Start?

查看:38
本文介绍了是否有与 Process.Start 等效的异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所暗示的那样,是否有我可以等待的 Process.Start(允许您运行另一个应用程序或批处理文件)的等效项?

Like the title suggests, is there an equivalent to Process.Start (allows you run another application or batch file) that I can await?

我正在使用一个小型控制台应用程序,这似乎是使用 async 和 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.

我的想法是这样的:

void async RunCommand()
{
    var result = await Process.RunAsync("command to run");
}

推荐答案

Process.Start() 只启动进程,不会等到进程结束,所以没有太大作用使它async 有意义.如果你还想这样做,你可以做类似await Task.Run(() => Process.Start(fileName))之类的事情.

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)).

但是,如果你想异步等待进程完成,你可以使用 Exited 事件TaskCompletionSource:

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;
}

这篇关于是否有与 Process.Start 等效的异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆