当前位置: 首页>>代码示例>>C#>>正文


C# Process.WaitForExitAsync方法代码示例

本文整理汇总了C#中System.Diagnostics.Process.WaitForExitAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Process.WaitForExitAsync方法的具体用法?C# Process.WaitForExitAsync怎么用?C# Process.WaitForExitAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Diagnostics.Process的用法示例。


在下文中一共展示了Process.WaitForExitAsync方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ExtractAsync

 static async Task ExtractAsync(string filename, string destination, Progress progress)
 {
     Directory.Delete(destination, true);
     Directory.CreateDirectory(destination);
     var workingDir = Paths.ExecutingDirPath;
     var args = $"x \"{filename}\" -o\"{destination}\" -y";
     var si = new ProcessStartInfo(@"tools\7z.exe", args)
     {
         WorkingDirectory = workingDir,
         RedirectStandardOutput = true,
         RedirectStandardError = true,
         RedirectStandardInput = true,
         UseShellExecute = false
     };
     using (var proc = new Process { StartInfo = si })
     {
         proc.Start();
         var exited = await proc.WaitForExitAsync(ExtractionTimeout);
         if (!exited)
         {
             proc.Kill();
             throw new TimeoutException($"Extraction of '{filename}' took longer than {ExtractionTimeout}, aborting");
         }
         if (proc.ExitCode != 0)
         {
             // TODO: better exception type
             throw new Exception(
                 $"Failed to extract archive '{filename}'. 7zip exit code: {proc.ExitCode}\n{proc.StandardOutput.ReadToEnd()}\n{proc.StandardError.ReadToEnd()}");
         }
         progress?.CompletedInstall();
     }
 }
开发者ID:mattolenik,项目名称:winston,代码行数:32,代码来源:ArchiveExtractor.cs

示例2: RunAsync

 public async Task<SimpleProcess> RunAsync(TimeSpan timeout)
 {
     Process = new Process { StartInfo = info };
     Process.Start();
     await Process.WaitForExitAsync(timeout);
     if (!Process.HasExited)
     {
         Process.Kill();
     }
     StdOut = Process.StandardOutput.ReadToEnd();
     StdErr = Process.StandardError.ReadToEnd();
     ExitCode = Process.ExitCode;
     return this;
 }
开发者ID:mattolenik,项目名称:winston,代码行数:14,代码来源:SimpleProcess.cs

示例3: ExecuteWin32ProcessAsync

		public static async Task<ProcessDetail> ExecuteWin32ProcessAsync(string executorPath, string arguments, string workingDirectory, int timeoutInMilliseconds)
		{
			var processDetail = new ProcessDetail { ExecutorPath = executorPath, Arguments = arguments, WorkingDirectory = workingDirectory, };

			// initialize compiler process 
			var process = new Process
			{
				StartInfo = new ProcessStartInfo
				{
					UseShellExecute = false,
					RedirectStandardError = true,
					RedirectStandardOutput = true,
					FileName = executorPath,
					Arguments = arguments,
					CreateNoWindow = true,
					WorkingDirectory = workingDirectory
				}
			};

			using (process)
			{
				var output = new StringBuilder();
				var error = new StringBuilder();
				process.OutputDataReceived += (s, e) => output.AppendLine(e.Data);
				process.ErrorDataReceived += (s, e) => error.AppendLine(e.Data);
				try
				{
					process.Start();
				}
				catch (Win32Exception e)
				{
					throw new Exception(e.Message + ":" + processDetail);
				}

				// Use async mode to avoid child process hung forever, e.g. AppLoc.exe will show GUI if input parameter is invalid 
				// Use async mode to avoid deadlock between WaitForExit and ReadToEnd 
				process.BeginOutputReadLine();
				process.BeginErrorReadLine();

				// Wait for process to exit within timeout 
				await process.WaitForExitAsync(timeoutInMilliseconds);

				processDetail.ExitCode = process.ExitCode;
				processDetail.StandardOutput = output.ToString();
				processDetail.StandardError = error.ToString();
				processDetail.ProcessId = process.Id;
				return processDetail;
			}
		}
开发者ID:zhangz,项目名称:Toolbox,代码行数:49,代码来源:ProcessUtility.cs

示例4: CheckedCall

        public async static Task CheckedCall(CancellationToken cancellationToken, 
            string fileName, 
            params string[] commands)
        {
            var p = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    FileName = fileName,
                    Arguments = String.Join(" ", commands),
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                }
            };

            p.Start();

            var outputs = new[] {
                Task.Factory.StartNew(() =>
                {
                    CopyTo(p.StandardError, _ => log.DebugFormat("{0}:out: {1}", p.Id, _));
                }, TaskCreationOptions.LongRunning),
                Task.Factory.StartNew(() =>
                {
                    CopyTo(p.StandardError, _ => log.DebugFormat("{0}:err: {1}", p.Id, _));
                }, TaskCreationOptions.LongRunning)
            };

            var stopwatch = Stopwatch.StartNew();
            log.DebugFormat("Process {0} started. {1}", p.Id, Details(p));

            await p.WaitForExitAsync(cancellationToken);
            Task.WaitAll(outputs);

            log.DebugFormat("Process {0} finished. Exit code: {1}. Run time: {2}. {3}",
                p.Id, p.ExitCode, stopwatch.Elapsed, Details(p));


            if (p.ExitCode != 0)
            {
                throw new Exception(String.Format("Exit code {0}: {1}", p.ExitCode, Details(p)));
            }
        }
开发者ID:sidiandi,项目名称:ttaudio,代码行数:45,代码来源:SubProcess.cs

示例5: CompressFileAsync

        public async Task<CompressionResult> CompressFileAsync(string fileName)
        {
            string targetFile = Path.ChangeExtension(Path.GetTempFileName(), Path.GetExtension(fileName));

            ProcessStartInfo start = new ProcessStartInfo("cmd")
            {
                WindowStyle = ProcessWindowStyle.Hidden,
                WorkingDirectory = Path.Combine(Path.GetDirectoryName(GetType().Assembly.Location), @"Resources\Tools\"),
                Arguments = GetArguments(fileName, targetFile),
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            var process = new Process();
            process.StartInfo = start;
            process.Start();
            await process.WaitForExitAsync();

            return new CompressionResult(fileName, targetFile);
        }
开发者ID:Kingefosa,项目名称:ImageOptimizer,代码行数:20,代码来源:Compressor.cs

示例6: Execute_RunBuildTools

        private async void Execute_RunBuildTools(object obj)
        {
            var argsBuilder = new StringBuilder();
            argsBuilder.Append("--login -i -c \"java -jar \"\"BuildTools.jar\"\"\"");

            if (!string.IsNullOrEmpty(BuildTool.SpigotVersion))
                argsBuilder.Append(" --rev " + BuildTool.SpigotVersion);

            using (var process = new Process())
            {
                process.StartInfo.FileName = BuildTool.GitBashFullName;
                process.StartInfo.WorkingDirectory = BuildTool.BuildToolsDirectory;
                process.StartInfo.Arguments = argsBuilder.ToString();
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardOutput = true;

                process.ErrorDataReceived += (sender, args) =>
                {
                    if (args.Data == null) return;
                    ConsoleOutput += (args.Data + Environment.NewLine);
                };

                process.OutputDataReceived += (sender, args) =>
                {
                    if (args.Data == null) return;
                    ConsoleOutput += (args.Data + Environment.NewLine);
                };

                process.Exited += (sender, args) =>
                {
                    var builtFilePath = Path.Combine(BuildTool.BuildToolsDirectory, @"Spigot\Spigot-Server\target");

                    if (Directory.Exists(builtFilePath))
                        Process.Start(builtFilePath);
                };

                process.Start();

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

                await process.WaitForExitAsync();
            }
        }
开发者ID:Hertizch,项目名称:HrtzCraft,代码行数:46,代码来源:BuildToolsViewModel.cs

示例7: UpdateFirmware

        private async Task UpdateFirmware(string firmwareFilePath)
        {
                    using (var sp = new SerialPort(SelectedComPort.ComPort, 1200, Parity.None, 8, StopBits.One))
                    {
                        sp.Open();
                        Thread.Sleep(100);
                        sp.Close();
                    }

                    var bossaFilePath = Path.Combine(Path.GetTempPath(), @"bossac.exe");
                    File.WriteAllBytes(bossaFilePath, Properties.Resources.BossaCmd);

                    var flashProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo(
                            bossaFilePath,
                            $"--port={SelectedComPort.ComPort} -U false -e -w -v -b \"{firmwareFilePath}\" -R")
                    };

                    flashProcess.Start();
                    await flashProcess.WaitForExitAsync();
                    var exitCode = flashProcess.ExitCode;

                    if (exitCode != 0)
                    {
                        await _dialogService.ShowMessage("Firmware could not be updated.", "Update");
                    }
                    else
                    {
                        await _dialogService.ShowMessage("Firmware update was successful.", "Update");
                    }

                    IsBusy = false;
        }
开发者ID:milindur,项目名称:MdkControllerUpdate,代码行数:34,代码来源:MainViewModel.cs

示例8: Execute_StartServer

        private async void Execute_StartServer(object obj)
        {
            if (ServerConfigViewModel.Instance.Server.IsRunning)
            {
                _inputWriter.WriteLine("stop");
                return;
            }

            using (var process = new Process())
            {
                process.StartInfo.FileName = ServerConfigViewModel.Instance.Server.JavaFullName;
                process.StartInfo.WorkingDirectory = ServerConfigViewModel.Instance.Server.ServerDirectory;
                process.StartInfo.Arguments = $"-Xms{ServerConfigViewModel.Instance.Server.RamAllocated}M -Xmx{ServerConfigViewModel.Instance.Server.RamMax}M -jar {ServerConfigViewModel.Instance.Server.JarFilename}";
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardInput = true;

                process.ErrorDataReceived += (sender, args) =>
                {
                    if (args.Data == null) return;
                    ProcessConsoleOutput(args.Data);
                };

                process.OutputDataReceived += (sender, args) =>
                {
                    if (args.Data == null) return;
                    ProcessConsoleOutput(args.Data);
                };

                process.Exited += (sender, args) =>
                {
                    ServerConfigViewModel.Instance.Server.IsRunning = false;
                };

                Exception exception = null;

                try
                {
                    process.Start();
                }
                catch (Exception ex)
                {
                    exception = ex;
                    Logger.Write("Could not start the server", true, exception);
                }
                finally
                {
                    if (exception == null)
                        ServerConfigViewModel.Instance.Server.IsRunning = true;
                }

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

                _inputWriter = process.StandardInput;
                _inputWriter.AutoFlush = true;

                await process.WaitForExitAsync();
            }
        }
开发者ID:Hertizch,项目名称:HrtzCraft,代码行数:62,代码来源:ServerControlViewModel.cs

示例9: Exec

        private async Task<string> Exec(string exe, string args)
        {
            var sb = new StringBuilder();
            var startinfo = new ProcessStartInfo(exe, args)
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                WorkingDirectory = _workingDirectory
            };
            var ret = new Process
            {
                StartInfo = startinfo,
                EnableRaisingEvents = true
            };
            ret.OutputDataReceived += (sender, eventArgs) =>
            {
                lock (sblock)
                {
                    var data = eventArgs.Data;
                    if (string.IsNullOrEmpty(data)) return;
                    sb.AppendLine(data);
                    Debug.Write(data);
                }
            };
            ret.ErrorDataReceived += (sender, eventArgs) =>
            {
                lock (sblock)
                {
                    var data = eventArgs.Data;
                    if (string.IsNullOrWhiteSpace(data)) return;
                    sb.AppendLine("ERROR: " + data);
                    Debug.Write(data);
                }
            };
            Debug.Assert(ret != null, "ret != null");
            if (_logger != null) _logger.LogInfo("» git " + args);
            ret.Start();
            ret.BeginOutputReadLine();
            ret.BeginErrorReadLine();
            await ret.WaitForExitAsync();
            lock (sblock)
            {
                return sb.ToString();
            }

        }
开发者ID:freeart,项目名称:FastKoala,代码行数:48,代码来源:GitExeWrapper.cs

示例10: LaunchPaymetheus

        public void LaunchPaymetheus()
        {
            if (Interlocked.Exchange(ref _paymetheusProcessStarted, 1) != 0)
                throw new InvalidOperationException("Paymetheus already started");

            const string processName = "Paymetheus";
            var fileName = processName;
            if (!parsedArguments.SearchPathForProcesses)
            {
                fileName = Portability.ExecutableInstallationPath(Environment.OSVersion.Platform, "Decred", processName);
            }

            var procInfo = new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = string.Join(" ", arguments), // pass arguments vertabim
                UseShellExecute = false,
            };
            _paymetheusProcess = Process.Start(procInfo);

            // For now only hide the launcher when running on mainnet.
            if (parsedArguments.IntendedNetwork == BlockChainIdentity.MainNet)
            {
                App.Current.Dispatcher.Invoke(() =>
                {
                    App.Current.MainWindow.Hide();
                });
            }

            Task.Run(async () =>
            {
                await _paymetheusProcess.WaitForExitAsync();
                if (parsedArguments.IntendedNetwork == BlockChainIdentity.MainNet)
                {
                    await App.Current.Dispatcher.InvokeAsync(() =>
                    {
                        App.Current.MainWindow.Show();
                    });
                }
                SignalConsensusServerShutdown();
            });
        }
开发者ID:decred,项目名称:Paymetheus,代码行数:42,代码来源:App.xaml.cs

示例11: LaunchConcensusServer

        public void LaunchConcensusServer(out AnonymousPipeServerStream rx, out AnonymousPipeServerStream tx)
        {
            if (Interlocked.Exchange(ref _consensusServerStarted, 1) != 0)
                throw new InvalidOperationException("Consensus server already started");

            const string processName = "dcrd";
            var fileName = processName;
            if (!parsedArguments.SearchPathForProcesses)
            {
                fileName = Portability.ExecutableInstallationPath(Environment.OSVersion.Platform, "Decred", processName);
            }

            var procInfo = new ProcessStartInfo
            {
                FileName = fileName,
                Arguments = $"--piperx {_outPipe.GetClientHandleAsString()} --pipetx {_inPipe.GetClientHandleAsString()} --lifetimeevents",
                CreateNoWindow = parsedArguments.IntendedNetwork == BlockChainIdentity.MainNet, // only hide on mainnet
                UseShellExecute = false,
            };
            if (parsedArguments.IntendedNetwork != BlockChainIdentity.MainNet)
            {
                procInfo.Arguments += $" --{parsedArguments.IntendedNetwork.Name}";
            }

            _consensusServerProcess = Process.Start(procInfo);

            rx = _inPipe;
            tx = _outPipe;

            Task.Run(async () =>
            {
                var exitCode = await _consensusServerProcess.WaitForExitAsync();
                if (exitCode != 0)
                {
                    MessageBox.Show($"Consensus server exited with code {exitCode}");
                }
                await Application.Current.Dispatcher.InvokeAsync(Application.Current.Shutdown);
            });
        }
开发者ID:decred,项目名称:Paymetheus,代码行数:39,代码来源:App.xaml.cs


注:本文中的System.Diagnostics.Process.WaitForExitAsync方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。