CommonProcess.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Model.Diagnostics;
  8. namespace Emby.Common.Implementations.Diagnostics
  9. {
  10. public class CommonProcess : IProcess
  11. {
  12. public event EventHandler Exited;
  13. private readonly ProcessOptions _options;
  14. private readonly Process _process;
  15. public CommonProcess(ProcessOptions options)
  16. {
  17. _options = options;
  18. var startInfo = new ProcessStartInfo
  19. {
  20. Arguments = options.Arguments,
  21. FileName = options.FileName,
  22. WorkingDirectory = options.WorkingDirectory,
  23. UseShellExecute = options.UseShellExecute,
  24. CreateNoWindow = options.CreateNoWindow,
  25. RedirectStandardError = options.RedirectStandardError,
  26. RedirectStandardInput = options.RedirectStandardInput,
  27. RedirectStandardOutput = options.RedirectStandardOutput
  28. };
  29. startInfo.ErrorDialog = options.ErrorDialog;
  30. if (options.IsHidden)
  31. {
  32. startInfo.WindowStyle = ProcessWindowStyle.Hidden;
  33. }
  34. _process = new Process
  35. {
  36. StartInfo = startInfo
  37. };
  38. if (options.EnableRaisingEvents)
  39. {
  40. _process.EnableRaisingEvents = true;
  41. _process.Exited += _process_Exited;
  42. }
  43. }
  44. private void _process_Exited(object sender, EventArgs e)
  45. {
  46. if (Exited != null)
  47. {
  48. Exited(this, e);
  49. }
  50. }
  51. public ProcessOptions StartInfo
  52. {
  53. get { return _options; }
  54. }
  55. public StreamWriter StandardInput
  56. {
  57. get { return _process.StandardInput; }
  58. }
  59. public StreamReader StandardError
  60. {
  61. get { return _process.StandardError; }
  62. }
  63. public StreamReader StandardOutput
  64. {
  65. get { return _process.StandardOutput; }
  66. }
  67. public int ExitCode
  68. {
  69. get { return _process.ExitCode; }
  70. }
  71. public void Start()
  72. {
  73. _process.Start();
  74. }
  75. public void Kill()
  76. {
  77. _process.Kill();
  78. }
  79. public bool WaitForExit(int timeMs)
  80. {
  81. return _process.WaitForExit(timeMs);
  82. }
  83. public Task<bool> WaitForExitAsync(int timeMs)
  84. {
  85. return Task.FromResult(_process.WaitForExit(timeMs));
  86. }
  87. public void Dispose()
  88. {
  89. _process.Dispose();
  90. }
  91. }
  92. }