Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ProcessUtils.cs - github.com/xamarin/macdoc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 39906bd51d19db57b7fe77f2300ed8aabe1faa01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// ProcessUtils.cs
//
// Author:
//       Jérémie Laval <jeremie.laval@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.

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

namespace macdoc
{
	public static class ProcessUtils
	{
		public static Task<int> StartProcess (ProcessStartInfo psi, TextWriter stdout, TextWriter stderr, CancellationToken cancellationToken)
		{
			var tcs = new TaskCompletionSource<int> ();
			if (cancellationToken.CanBeCanceled && cancellationToken.IsCancellationRequested) {
				tcs.SetCanceled ();
				return tcs.Task;
			}

			psi.UseShellExecute = false;
			if (stdout != null) {
				psi.RedirectStandardOutput = true;
			}
			if (stderr != null) {
				psi.RedirectStandardError = true;
			}
			var p = Process.Start (psi);
			if (cancellationToken.CanBeCanceled)
				cancellationToken.Register (() => {
					try {
						if (!p.HasExited) {
							p.Kill ();
						}
					} catch (InvalidOperationException ex) {
						if (ex.Message.IndexOf ("already exited") < 0)
							throw;
					}
				});
			p.EnableRaisingEvents = true;
			if (psi.RedirectStandardOutput) {
				bool stdOutInitialized = false;
				p.OutputDataReceived += (sender, e) => {
					try {
						if (stdOutInitialized)
							stdout.WriteLine ();
						stdout.Write (e.Data);
						stdOutInitialized = true;
					} catch (Exception ex) {
						tcs.SetException (ex);
					}
				};
				p.BeginOutputReadLine ();
			}
			if (psi.RedirectStandardError) {
				bool stdErrInitialized = false;
				p.ErrorDataReceived += (sender, e) => {
					try {
						if (stdErrInitialized)
							stderr.WriteLine ();
						stderr.Write (e.Data);
						stdErrInitialized = true;
					} catch (Exception ex) {
						tcs.SetException (ex);
					}
				};
				p.BeginErrorReadLine ();
			}
			p.Exited += (sender, e) => tcs.SetResult (p.ExitCode);

			return tcs.Task;
		}

		public static void StartRelaunchProcess ()
		{

		}
	}
}