简体   繁体   English

如何在线程中启动进程

[英]How to start a Process in a Thread


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 within threads - or even if that is viable.进一步编辑以下不是生产代码 - 我只是在玩几个类试图弄清楚我如何在线程中运行进程 - 或者即使这是可行的。 I've read various definitions on MSDN but am a newbie to threads and processes so any further definitive references to articles would be appreciated我已经阅读了 MSDN 上的各种定义,但我是线程和进程的新手,因此对文章的任何进一步明确引用将不胜感激


this is fine...这可以...

class Program {
    static void Main(string[] args) {

        Notepad np = new Notepad();
        Thread th = new Thread(new ThreadStart(np.startNPprocess));
        th.Start();

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
}

public class Notepad {

    public void startNPprocess() {

        Process pr = new Process();
        ProcessStartInfo prs = new ProcessStartInfo();
        prs.FileName = @"notepad.exe";
        pr.StartInfo = prs;
        pr.Start();     

    }
}

this isn't...这不是……

class Program {
    static void Main(string[] args) {


        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();


        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }
}

Why does the second not do the same as the first?为什么第二个和第一个不一样? In the second script I'm trying to pass Process.Start using the Threadstart delegate ...I thought this would be ok as its a void method?在第二个脚本中,我试图使用 Threadstart 委托传递Process.Start ......我认为这可以作为它的void方法吗? Is the first script the only option or can I change the second slightly so that it effectively does the same job as the first ie start an instance of Notepad in a specified thread?第一个脚本是唯一的选择还是我可以稍微更改第二个脚本以便它有效地执行与第一个相同的工作,即在指定线程中启动记事本实例?


EDIT编辑

Some background as to why I'm playing around with this code: ultimately I need to build an application which will be running several Excel processes simultaneously.关于为什么我玩这个代码的一些背景:最终我需要构建一个将同时运行多个 Excel 进程的应用程序。 These processes can be troublesome when VBA errors as it results in a dialogbox.当 VBA 出错时,这些过程会很麻烦,因为它会导致一个对话框。 So I thought if each process was running in a thread then if a particular thread has been running for too long then I could kill the thread.所以我想如果每个进程都在一个线程中运行,那么如果一个特定的线程运行了太长时间,那么我可以杀死该线程。 I'm a newbie to Threads/Processes so basically playing around with possibilities at the moment.我是线程/进程的新手,所以目前基本上是在尝试各种可能性。

A ThreadStart expects a delegate that returns void . ThreadStart需要一个返回void的委托。 Process.Start returns bool , so is not a compatible signature. Process.Start返回bool ,因此不是兼容的签名。 You can swallow the return value in by using a lambda that gives you a delegate of the correct return type (ie void ) as follows:您可以通过使用 lambda 来吞下返回值,该 lambda 为您提供正确返回类型(即void )的委托,如下所示:

    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.当然,一个进程在一个新进程(一组完全独立的线程)中启动,所以在一个线程上启动它是完全没有意义的。

您可以进行更改,例如

ThreadStart ths = new ThreadStart(delegate() { pr.Start(); });

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.当您可以直接执行“cmd.exe”时,这就像运行一个执行“cmd.exe”的批处理文件……您所做的只是无所事事。 Don't reinvent the wheel and play easy :P不要重新发明轮子并轻松玩:P

Not answering directly the OP, but as this thread helped me track the right direction, I do want to answer this:不直接回答 OP,但由于此线程帮助我跟踪了正确的方向,我确实想回答这个问题:

"starting it on a thread is completely pointless" “在线程上启动它是完全没有意义的”

I have a .Net server that uses NodeJS as its TCP socket manager.我有一个使用 NodeJS 作为其 TCP 套接字管理器的 .Net 服务器。 I wanted the NodeJS to write to the same output as the .Net server and they both run in parallel.我希望 NodeJS 写入与 .Net 服务器相同的输出,并且它们都并行运行。 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.同时不阻塞 .Net 服务器的主线程。

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.我希望它对某人有意义,如果您有更好的方法来实现我刚刚描述的内容,我会很高兴听到。

You can start the process in another thread by using the start keyword like below this cod:您可以使用如下代码中的 start 关键字在另一个线程中启动进程:

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

in this way, your GUI program doesn't freeze when you run the notepad.这样,当您运行记事本时,您的 GUI 程序不会冻结。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM