プロセス起動exe,当.exe内部に異常が投げ出されると、常にエラープロンプトボックスがポップアップされ、Processの終了を阻止します.

9911 ワード

 1 public class TaskProcess

 2     {

 3         [DllImport("kernel32.dll", SetLastError = true)]

 4         public static extern int SetErrorMode(int wMode);

 5 

 6         public Process process { get; set; }

 7 

 8         public void Do()

 9         {

10             try

11             {

12                 int oldMode = SetErrorMode(3);

13 

14                 this.process = new Process();

15                 this.process.EnableRaisingEvents = true;

16                 this.process.StartInfo.FileName = @"\\172.21.11.10\File\Platform\ExecuteFile\LSystem.exe";

17                 this.process.StartInfo.Arguments = @"8 \\172.21.11.10\File\Platform\Configuration\AppSettings.config 17 1 0";

18                 this.process.StartInfo.RedirectStandardError = true;

19                 this.process.StartInfo.RedirectStandardInput = true;

20                 this.process.StartInfo.RedirectStandardOutput = true;

21                 this.process.StartInfo.CreateNoWindow = false;

22                 this.process.StartInfo.ErrorDialog = false;

23                 this.process.StartInfo.UseShellExecute = false;

24                 this.process.Start();

25 

26                 SetErrorMode(oldMode);

27 

28                 ThreadPool.QueueUserWorkItem(DoWork, process);

29 

30                 process.WaitForExit();

31 

32                 Console.WriteLine("ExitCode is " + this.process.ExitCode);

33             }

34             catch (Exception ex)

35             {

36                 Console.WriteLine(ex.Message);

37                 Console.WriteLine(ex.StackTrace);

38             }

39         }

40 

41         public ArrayList Out = ArrayList.Synchronized(new ArrayList());

42 

43         private void DoWork(object state)

44         {

45             Process process = state as Process;

46 

47             if (process != null)

48             {

49                 try

50                 {

51                     string line = process.StandardOutput.ReadLine();

52 

53                     do

54                     {

55                         Out.Add(line);

56 

57                         line = process.StandardOutput.ReadLine();

58                         Console.WriteLine(line);

59                     }

60                     while (line != null);

61 

62                     process.StandardInput.WriteLine("exit");

63                 }

64                 catch (Exception ex)

65                 {

66                     Console.WriteLine(ex.Message);

67                     Console.WriteLine(ex.StackTrace);

68                 }

69             }

70         }

71     }

参考記事:
http://stackoverflow.com/questions/673036/how-to-handle-a-crash-in-a-process-launched-via-system-diagnostics-process