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

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

问题描述

之类的标题所暗示的,是有一个相当于的Process.Start (允许您运行其他应用程序或批处理文件),我可以等待?

我在玩一个小控制台应用程序,这似乎像是一个完美的地方,使用异步和等待,但我不能找到这种情况下的任何文件。

我在想什么是沿着这些路线的东西:

 无效异步RunCommand()
{
    VAR的结果=等待Process.RunAsync(命令运行);
}


解决方案

的Process.Start()只启动过程,它不会等到它完成,所以它并没有多大意义,使其异步。如果您仍然想这样做,你可以这样做等待Task.Run(()=>的Process.Start(文件名))。

但是,如果你希望异步等待进程结束,您可以使用已退出事件与<一起来的href=\"http://msdn.microsoft.com/en-us/library/dd449174.aspx\"><$c$c>TaskCompletionSource:

 静态任务RunProcessAsync(字符串文件名)
{
    //没有非通用TaskCompletionSource
    VAR TCS =新TaskCompletionSource&LT;布尔&GT;();    VAR工艺=新工艺
    {
        的StartInfo = {文件名=文件名},
        EnableRaisingEvents =真
    };    process.Exited + =(发件人,参数)=&GT;
    {
        tcs.SetResult(真);
        process.Dispose();
    };    的Process.Start();    返回tcs.Task;
}

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 RunProcessAsync(string fileName)
{
    // there is no non-generic TaskCompletionSource
    var tcs = new TaskCompletionSource<bool>();

    var process = new Process
    {
        StartInfo = { FileName = fileName },
        EnableRaisingEvents = true
    };

    process.Exited += (sender, args) =>
    {
        tcs.SetResult(true);
        process.Dispose();
    };

    process.Start();

    return tcs.Task;
}

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

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