[Mono-list] System.Diagnostic.Process and event handlers

noda www.bgr at free.fr
Wed Feb 2 16:09:31 EST 2011


Just in case of interest, while making some tests before submitting my bug
report, I've been able to confirm the mono bug and also find a workaround in
the meanwhile.

The workaround (and somehow the proof of the bug) is to to do the
asynchronous standard output / event dispatch yourself, and it works
perfectly:

        public static bool HasStarted(Process proc)
        {
            try 
            {
                return (proc != null && !proc.HasExited && proc.Id != 0);
            }
            catch
            {
                return false;
            }
        }

        private void asyncReadStandardOutput()
        {
            try
            {
                do 
                {
                    string line = proc.StandardOutput.ReadLine();
                    if (line != null) {
                        // forward event here, or do something you want with
the line
                    }
                } 
                while (!proc.HasExited);
            }
            catch
            { }
        }

and in your code:

               proc = new Process();
                proc.StartInfo.FileName = "aProgram";
                proc.StartInfo.WorkingDirectory =
Path.GetDirectoryName(proc.StartInfo.FileName);
                proc.StartInfo.UseShellExecute = false;;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.CreateNoWindow = true;

                proc.Start();

                // work around mono bug while forwarding asynchronously
console output events
                while (!HasStarted(proc))
                    Thread.Sleep(1);

                Thread t1 = new Thread(asyncReadStandardOutput);
                t1.Start();
                
                proc.WaitForExit();				
                proc.Close();


I dislike using such Exception handling as part of the program, but for now
I haven't found any other way to work around this bug. 

-- 
View this message in context: http://mono.1490590.n4.nabble.com/System-Diagnostic-Process-and-event-handlers-tp3246096p3255815.html
Sent from the Mono - General mailing list archive at Nabble.com.


More information about the Mono-list mailing list