How to start a Process in a Thread

前端 未结 5 474
陌清茗
陌清茗 2021-01-02 08:45

FURTHER EDIT the following is not production code - I\'m just playing around with a couple of classes trying to figure out how I run processes wit

相关标签:
5条回答
  • 2021-01-02 08:57

    You can start the process in another thread by using the start keyword like below this cod:

    Process.Start("start notepad.exe");
    

    in this way, your GUI program doesn't freeze when you run the notepad.

    0 讨论(0)
  • 2021-01-02 08:58

    you can make changes like

    ThreadStart ths = new ThreadStart(delegate() { pr.Start(); });
    
    0 讨论(0)
  • 2021-01-02 09:09

    A ThreadStart expects a delegate that returns void. Process.Start returns bool, so is not a compatible signature. You can swallow the return value in by using a lambda that gives you a delegate of the correct return type (i.e. void) as follows:

        Process pr = new Process();
        ProcessStartInfo prs = new ProcessStartInfo();
        prs.FileName = @"notepad.exe";
        pr.StartInfo = prs;
    
        ThreadStart ths = new ThreadStart(() => pr.Start());
        Thread th = new Thread(ths);
        th.Start();
    

    ...but it's probably advisable to check the return value:

        ThreadStart ths = new ThreadStart(() => {
            bool ret = pr.Start();
            //is ret what you expect it to be....
        });
    

    Of course, a process starts in a new process (a completely separate bunch of threads), so starting it on a thread is completely pointless.

    0 讨论(0)
  • 2021-01-02 09:12

    Just start the process normally using this code:

    Process.Start("notepad.exe");
    

    There is no point and no benefits in creating a thread to run a new process. It's like running a batch file that executes "cmd.exe" when you can directly execute "cmd.exe"... you are just doing more than what's necessary for nothing. Don't reinvent the wheel and play easy :P

    0 讨论(0)
  • 2021-01-02 09:18

    Not answering directly the OP, but as this thread helped me track the right direction, I do want to answer this:

    "starting it on a thread is completely pointless"

    I have a .Net server that uses NodeJS as its TCP socket manager. I wanted the NodeJS to write to the same output as the .Net server and they both run in parallel. So opening in a new thread allowed me to use

    processNodeJS.BeginErrorReadLine()
    processNodeJS.BeginOutputReadLine()
    processNodeJS.WaitForExit()
    

    while not blocking the main thread of the .Net server.

    I hope it makes sense to someone and if you have a better way to implement what I've just described, I'll be more than happy to hear.

    0 讨论(0)
提交回复
热议问题