How to start a Process in a Thread

前端 未结 5 491
陌清茗
陌清茗 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 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.

提交回复
热议问题