views:

95

answers:

1

I'm calling Process.Start, but it blocks the current thread.

pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");

// Start process
mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
    Trace.TraceError("Unable to run process {0}.");
}

Even when the process is closed, the code doesn't respond anymore.

But Process.Start is really supposed to block? What's going on?

(The process start correctly)


using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;

namespace Test
{
    class Test
    {
        [STAThread]
        public static void Main()
        {
            Thread ServerThread = new Thread(AccepterThread);
            ServerThread.Start();

            Console.WriteLine (" ---  Press ENTER to stop service ---");
            while (Console.Read() < 0) { Application.DoEvents(); }

            Console.WriteLine("Done.");
        }

        public static void AccepterThread(object data)
        {
            bool accepted = false;

            while (true) {
                if (accepted == false) {
                    Thread hThread = new Thread(HandlerThread);
                    accepted = true;
                    hThread.Start();
                } else
                    Thread.Sleep(100);
            }
        }

        public static void HandlerThread(object data)
        {
            ProcessStartInfo pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");

            Console.WriteLine("Starting process.");

            // Start process
            Process mProcess = new Process();
            mProcess.StartInfo = pInfo;
            if (mProcess.Start() == false) {
                Console.WriteLine("Unable to run process.");
            }
            Console.WriteLine("Still living...");
        }
    }
}

Console output is:

--- Press ENTER to stop service --- Starting process.


Found it:

[STAThread]

Makes the Process.Start blocking. I read STAThread and Multithreading, but I cannot link the concepts with Process.Start behavior.

AFAIK, STAThread is required by Windows.Form. How to workaround this problem when using Windows.Form?


News for the hell:

If I rebuild my application, the first time I run application work correctly, but if I stop debugging and restart iy again, the problem araise.

The problem is not raised when application is executed without the debugger.

+4  A: 

No, Process.Start doesn't normally block... otherwise you wouldn't be able to use features like redirected I/O.

Sample console app:

using System;
using System.Diagnostics;

public class Test
{
    static void Main()
    {
        Process p = new Process { 
            StartInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe")
        };
        p.Start();
        Console.WriteLine("See, I'm still running");
    }
}

This prints "See, I'm still running" with no problems on my box - what's it doing on your box?

Jon Skeet