是否存在与Process.Start异步的等效项?


141

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

我正在玩一个小型控制台应用程序,这似乎是使用异步和等待的理想场所,但我找不到这种情况的任何文档。

我在想的是以下几方面的东西:

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

2
为什么不只对返回的Process对象使用WaitForExit?
SimpleVar 2012年

2
顺便说一句,听起来更像是您在寻找“同步”解决方案,而不是“异步”解决方案,因此标题具有误导性。
SimpleVar 2012年

2
@YoryeNathan-大声笑 确实,Process.Start async且OP似乎需要同步版本。
奥德

10
OP正在谈论C#5中的新async / await关键字
阿奎那(Aquinas),2012年

4
好的,我已经更新了我的帖子,使其更加清晰。我为什么要这样做的解释很简单。设想一个场景,在该场景中,您必须运行外部命令(诸如7zip之类的东西),然后继续应用程序的流程。这正是async / await旨在促进的目的,但似乎没有办法运行进程并等待其退出。
linkerro

Answers:


196

Process.Start()仅启动该过程,它不会等到完成为止,因此进行该过程没有多大意义async。如果您仍然想这样做,可以执行await Task.Run(() => Process.Start(fileName))

但是,如果您要异步等待过程完成,则可以Exited事件与一起使用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;
}

36
最后,我终于在github上贴上了一些东西-它没有取消/超时支持,但至少会为您收集标准输出和标准错误。 github.com/jamesmanning/RunProcessAsTask
James Manning

3
MedallionShell NuGet程序包中也提供了此功能
ChaseMedallion,2014年

8
确实很重要:使用设置各种属性processprocess.StartInfo更改其运行顺序的顺序.Start()。例如,如果您.EnableRaisingEvents = true在设置StartInfo属性之前先进行调用(如此处所示),则一切正常。如果稍后进行设置(例如,将其与保持在一起).Exited,即使您之前调用过它.Start(),它也无法正常工作- .Exited立即触发,而不是等待流程实际退出。不知道为什么,只需要小心一点。
克里斯·莫斯基尼

2
@svick在窗口表单中,process.SynchronizingObject应将其设置为表单组件,以避免在单独的线程上调用处理事件的方法(例如Exited,OutputDataReceived,ErrorDataReceived)。
KevinBui

4
没有实际意义的,包裹Process.StartTask.Run。例如,UNC路径将被同步解析。该摘录最多可能需要30秒才能完成:Process.Start(@"\\live.sysinternals.com\whatever")
Jabe

55

这是我根据svick的回答得出的结论。它增加了输出重定向,退出代码保留和稍微更好的错误处理(Process即使无法启动也要处理对象):

public static async Task<int> RunProcessAsync(string fileName, string args)
{
    using (var process = new Process
    {
        StartInfo =
        {
            FileName = fileName, Arguments = args,
            UseShellExecute = false, CreateNoWindow = true,
            RedirectStandardOutput = true, RedirectStandardError = true
        },
        EnableRaisingEvents = true
    })
    {
        return await RunProcessAsync(process).ConfigureAwait(false);
    }
}    
private static Task<int> RunProcessAsync(Process process)
{
    var tcs = new TaskCompletionSource<int>();

    process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
    process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
    process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);

    bool started = process.Start();
    if (!started)
    {
        //you may allow for the process to be re-used (started = false) 
        //but I'm not sure about the guarantees of the Exited event in such a case
        throw new InvalidOperationException("Could not start process: " + process);
    }

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return tcs.Task;
}

1
刚刚找到了这个有趣的解决方案。由于我是C#的新手,因此不确定如何使用async Task<int> RunProcessAsync(string fileName, string args)。我修改了此示例,并一一传递了三个对象。我该如何等待引发事件?例如。在我的申请停下来之前..非常感谢
marrrschine '16

3
@marrrschine我不明白您的意思,也许您应该使用一些代码开始一个新问题,以便我们可以看到您尝试过的内容并从那里继续。
Ohad Schneider

4
很棒的答案。谢谢svick奠定了基础,也感谢Ohad进行了非常有用的扩展。
Gordon Bean

1
@SuperJMN读取代码(referencesource.microsoft.com/#System/services/monitoring/…)我不认为Dispose事件处理程序为null,因此从理论上讲,如果您调用Dispose了该引用,但仍然保留了该引用,那么我相信这将是一个泄漏。但是,当不再有对该Process对象的引用并且该对象被(垃圾)收集时,将没有任何一个指向事件处理程序列表。因此它被收集了,现在列表中没有对以前的委托的引用,因此最终他们被垃圾收集了。
Ohad Schneider

1
@SuperJMN:有趣的是,它比这更复杂/更强大。首先,Dispose清理一些资源,但不能防止泄漏的引用保持process存在。实际上,您会注意到process指向处理程序,但是Exited处理程序也具有对的引用process。在某些系统中,该循环引用将阻止垃圾回收,但是.NET中使用的算法仍将允许清除所有内容,只要所有内容都位于没有外部引用的“岛”上即可。
TheRubberDuck

4

这是另一种方法。与svickOhad的答案类似的概念,但是对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
}

4

我建立了一个班来开始一个过程,由于各种要求,在过去的几年中它一直在增长。在使用过程中,我发现Process类在处理甚至读取ExitCode方面存在一些问题。因此,这完全由我的班级解决。

该类具有多种可能性,例如读取输出,以Admin或其他用户身份启动,捕获异常以及还启动所有这些异步incl。消除。很好的是,在执行期间也可以读取输出。

public class ProcessSettings
{
    public string FileName { get; set; }
    public string Arguments { get; set; } = "";
    public string WorkingDirectory { get; set; } = "";
    public string InputText { get; set; } = null;
    public int Timeout_milliseconds { get; set; } = -1;
    public bool ReadOutput { get; set; }
    public bool ShowWindow { get; set; }
    public bool KeepWindowOpen { get; set; }
    public bool StartAsAdministrator { get; set; }
    public string StartAsUsername { get; set; }
    public string StartAsUsername_Password { get; set; }
    public string StartAsUsername_Domain { get; set; }
    public bool DontReadExitCode { get; set; }
    public bool ThrowExceptions { get; set; }
    public CancellationToken CancellationToken { get; set; }
}

public class ProcessOutputReader   // Optional, to get the output while executing instead only as result at the end
{
    public event TextEventHandler OutputChanged;
    public event TextEventHandler OutputErrorChanged;
    public void UpdateOutput(string text)
    {
        OutputChanged?.Invoke(this, new TextEventArgs(text));
    }
    public void UpdateOutputError(string text)
    {
        OutputErrorChanged?.Invoke(this, new TextEventArgs(text));
    }
    public delegate void TextEventHandler(object sender, TextEventArgs e);
    public class TextEventArgs : EventArgs
    {
        public string Text { get; }
        public TextEventArgs(string text) { Text = text; }
    }
}

public class ProcessResult
{
    public string Output { get; set; }
    public string OutputError { get; set; }
    public int ExitCode { get; set; }
    public bool WasCancelled { get; set; }
    public bool WasSuccessful { get; set; }
}

public class ProcessStarter
{
    public ProcessResult Execute(ProcessSettings settings, ProcessOutputReader outputReader = null)
    {
        return Task.Run(() => ExecuteAsync(settings, outputReader)).GetAwaiter().GetResult();
    }

    public async Task<ProcessResult> ExecuteAsync(ProcessSettings settings, ProcessOutputReader outputReader = null)
    {
        if (settings.FileName == null) throw new ArgumentNullException(nameof(ProcessSettings.FileName));
        if (settings.Arguments == null) throw new ArgumentNullException(nameof(ProcessSettings.Arguments));

        var cmdSwitches = "/Q " + (settings.KeepWindowOpen ? "/K" : "/C");

        var arguments = $"{cmdSwitches} {settings.FileName} {settings.Arguments}";
        var startInfo = new ProcessStartInfo("cmd", arguments)
        {
            UseShellExecute = false,
            RedirectStandardOutput = settings.ReadOutput,
            RedirectStandardError = settings.ReadOutput,
            RedirectStandardInput = settings.InputText != null,
            CreateNoWindow = !(settings.ShowWindow || settings.KeepWindowOpen),
        };
        if (!string.IsNullOrWhiteSpace(settings.StartAsUsername))
        {
            if (string.IsNullOrWhiteSpace(settings.StartAsUsername_Password))
                throw new ArgumentNullException(nameof(ProcessSettings.StartAsUsername_Password));
            if (string.IsNullOrWhiteSpace(settings.StartAsUsername_Domain))
                throw new ArgumentNullException(nameof(ProcessSettings.StartAsUsername_Domain));
            if (string.IsNullOrWhiteSpace(settings.WorkingDirectory))
                settings.WorkingDirectory = Path.GetPathRoot(Path.GetTempPath());

            startInfo.UserName = settings.StartAsUsername;
            startInfo.PasswordInClearText = settings.StartAsUsername_Password;
            startInfo.Domain = settings.StartAsUsername_Domain;
        }
        var output = new StringBuilder();
        var error = new StringBuilder();
        if (!settings.ReadOutput)
        {
            output.AppendLine($"Enable {nameof(ProcessSettings.ReadOutput)} to get Output");
        }
        if (settings.StartAsAdministrator)
        {
            startInfo.Verb = "runas";
            startInfo.UseShellExecute = true;  // Verb="runas" only possible with ShellExecute=true.
            startInfo.RedirectStandardOutput = startInfo.RedirectStandardError = startInfo.RedirectStandardInput = false;
            output.AppendLine("Output couldn't be read when started as Administrator");
        }
        if (!string.IsNullOrWhiteSpace(settings.WorkingDirectory))
        {
            startInfo.WorkingDirectory = settings.WorkingDirectory;
        }
        var result = new ProcessResult();
        var taskCompletionSourceProcess = new TaskCompletionSource<bool>();

        var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
        try
        {
            process.OutputDataReceived += (sender, e) =>
            {
                if (e?.Data != null)
                {
                    output.AppendLine(e.Data);
                    outputReader?.UpdateOutput(e.Data);
                }
            };
            process.ErrorDataReceived += (sender, e) =>
            {
                if (e?.Data != null)
                {
                    error.AppendLine(e.Data);
                    outputReader?.UpdateOutputError(e.Data);
                }
            };
            process.Exited += (sender, e) =>
            {
                try { (sender as Process)?.WaitForExit(); } catch (InvalidOperationException) { }
                taskCompletionSourceProcess.TrySetResult(false);
            };

            var success = false;
            try
            {
                process.Start();
                success = true;
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                if (ex.NativeErrorCode == 1223)
                {
                    error.AppendLine("AdminRights request Cancelled by User!! " + ex);
                    if (settings.ThrowExceptions) taskCompletionSourceProcess.SetException(ex); else taskCompletionSourceProcess.TrySetResult(false);
                }
                else
                {
                    error.AppendLine("Win32Exception thrown: " + ex);
                    if (settings.ThrowExceptions) taskCompletionSourceProcess.SetException(ex); else taskCompletionSourceProcess.TrySetResult(false);
                }
            }
            catch (Exception ex)
            {
                error.AppendLine("Exception thrown: " + ex);
                if (settings.ThrowExceptions) taskCompletionSourceProcess.SetException(ex); else taskCompletionSourceProcess.TrySetResult(false);
            }
            if (success && startInfo.RedirectStandardOutput)
                process.BeginOutputReadLine();
            if (success && startInfo.RedirectStandardError)
                process.BeginErrorReadLine();
            if (success && startInfo.RedirectStandardInput)
            {
                var writeInputTask = Task.Factory.StartNew(() => WriteInputTask());
            }

            async void WriteInputTask()
            {
                var processRunning = true;
                await Task.Delay(50).ConfigureAwait(false);
                try { processRunning = !process.HasExited; } catch { }
                while (processRunning)
                {
                    if (settings.InputText != null)
                    {
                        try
                        {
                            await process.StandardInput.WriteLineAsync(settings.InputText).ConfigureAwait(false);
                            await process.StandardInput.FlushAsync().ConfigureAwait(false);
                            settings.InputText = null;
                        }
                        catch { }
                    }
                    await Task.Delay(5).ConfigureAwait(false);
                    try { processRunning = !process.HasExited; } catch { processRunning = false; }
                }
            }

            if (success && settings.CancellationToken != default(CancellationToken))
                settings.CancellationToken.Register(() => taskCompletionSourceProcess.TrySetResult(true));
            if (success && settings.Timeout_milliseconds > 0)
                new CancellationTokenSource(settings.Timeout_milliseconds).Token.Register(() => taskCompletionSourceProcess.TrySetResult(true));

            var taskProcess = taskCompletionSourceProcess.Task;
            await taskProcess.ConfigureAwait(false);
            if (taskProcess.Result == true) // process was cancelled by token or timeout
            {
                if (!process.HasExited)
                {
                    result.WasCancelled = true;
                    error.AppendLine("Process was cancelled!");
                    try
                    {
                        process.CloseMainWindow();
                        await Task.Delay(30).ConfigureAwait(false);
                        if (!process.HasExited)
                        {
                            process.Kill();
                        }
                    }
                    catch { }
                }
            }
            result.ExitCode = -1;
            if (!settings.DontReadExitCode)     // Reason: sometimes, like when timeout /t 30 is started, reading the ExitCode is only possible if the timeout expired, even if process.Kill was called before.
            {
                try { result.ExitCode = process.ExitCode; }
                catch { output.AppendLine("Reading ExitCode failed."); }
            }
            process.Close();
        }
        finally { var disposeTask = Task.Factory.StartNew(() => process.Dispose()); }    // start in new Task because disposing sometimes waits until the process is finished, for example while executing following command: ping -n 30 -w 1000 127.0.0.1 > nul
        if (result.ExitCode == -1073741510 && !result.WasCancelled)
        {
            error.AppendLine($"Process exited by user!");
        }
        result.WasSuccessful = !result.WasCancelled && result.ExitCode == 0;
        result.Output = output.ToString();
        result.OutputError = error.ToString();
        return result;
    }
}

1

我认为您应该使用的是:

using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

namespace Extensions
{
    public static class ProcessExtensions
    {
        public static async Task<int> WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
        {
            process = process ?? throw new ArgumentNullException(nameof(process));
            process.EnableRaisingEvents = true;

            var completionSource = new TaskCompletionSource<int>();

            process.Exited += (sender, args) =>
            {
                completionSource.TrySetResult(process.ExitCode);
            };
            if (process.HasExited)
            {
                return process.ExitCode;
            }

            using var registration = cancellationToken.Register(
                () => completionSource.TrySetCanceled(cancellationToken));

            return await completionSource.Task.ConfigureAwait(false);
        }
    }
}

用法示例:

public static async Task<int> StartProcessAsync(ProcessStartInfo info, CancellationToken cancellationToken = default)
{
    path = path ?? throw new ArgumentNullException(nameof(path));
    if (!File.Exists(path))
    {
        throw new ArgumentException(@"File is not exists", nameof(path));
    }

    using var process = Process.Start(info);
    if (process == null)
    {
        throw new InvalidOperationException("Process is null");
    }

    try
    {
        return await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
    }
    catch (OperationCanceledException)
    {
        process.Kill();

        throw;
    }
}

接受CancellationToken,如果没有取消的话有Kill什么意义呢?
Theodor Zoulias

CancellationTokenWaitForExitAsync方法只需要能够取消等待或设置超时即可。可以通过以下方式来终止进程StartProcessAsync:```try {等待进程。WaitForExitAsync(cancellationToken); } catch(OperationCanceledException){process.Kill(); }`
康斯坦丁S.

我的观点是,当方法接受a时CancellationToken,取消令牌应该导致操作的取消,而不是等待的取消。这就是方法的调用者通常期望的。如果调用方只想取消等待中的操作,而让该操作仍在后台运行,那么从外部进行操作就很容易了(是一种扩展方法AsCancelable)。
Theodor Zoulias

我认为此决定应由调用方做出(特别是在这种情况下,因为此方法以Wait开始,通常我同意您的意见),如新的用法示例中所示。
Konstantin S.

0

我真的很担心进程的处理,如何等待异步退出呢?这是我的建议(基于之前的建议):

public static class ProcessExtensions
{
    public static Task WaitForExitAsync(this Process process)
    {
        var tcs = new TaskCompletionSource<object>();
        process.EnableRaisingEvents = true;
        process.Exited += (s, e) => tcs.TrySetResult(null);
        return process.HasExited ? Task.CompletedTask : tcs.Task;
    }        
}

然后,像这样使用它:

public static async Task<int> ExecAsync(string command, string args)
{
    ProcessStartInfo psi = new ProcessStartInfo();
    psi.FileName = command;
    psi.Arguments = args;

    using (Process proc = Process.Start(psi))
    {
        await proc.WaitForExitAsync();
        return proc.ExitCode;
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.