首页 > 其他 > 详细

How to use System.Diagnostics.Process correctly

时间:2015-02-04 14:21:55      阅读:205      评论:0      收藏:0      [点我收藏+]

I’ve seen many a question on stackoverflow and other places about running a process and capturing it’s output. Using the System.Diagnostics.Process correctly is not easy and most often it’s done wrong.

Some common mistakes with System.Diagnostics.Process:

  1. Not capturing both output streams (error & output)
  2. Not redirecting input can cause applications to hang
  3. Not closing redirected input can cause applications to hang
  4. Not calling BeginOutputReadLine/BeginErrorReadLine when using events
  5. Using OutputDataReceived/ErrorDataReceived without waiting for null
  6. Not checking for null in OutputDataReceived/ErrorDataReceived handlers
  7. Forgetting to set EnableRaisingEvents = true; when using the Exited event
  8. Forgetting ErrorDialog, CreateNoWindow, or UseShellExecute settings
  9. Incorrect handling of StandardOutput or StandardError stream readers

 

So with this said, here are some basic guidelines:

  1. Use the OutputDataReceived/ErrorDataRecieved events NOT the StandardOutput or StandardError. This will save you a lot of headache and needless thread management.
  2. Always capture all output AND input, if you don’t plan to provide input, close the stream immediately.
  3. Your process isn’t done until it exited AND you have read all the data. OutputDataReceived CAN AND WILL be fired after a call to WaitForExit() returns. You will need wait handles for each output stream and set the wait handle once your receive (null) data.

 

Additional Resources:

How to use System.Diagnostics.Process correctly

原文:http://www.cnblogs.com/olartan/p/4272192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!