gpt4 book ai didi

c# - 如何在线程中启动进程

转载 作者:可可西里 更新时间:2023-11-01 08:51:16 26 4
gpt4 key购买 nike


进一步编辑以下不是生产代码——我只是在玩弄几个类,试图弄清楚我如何在线程内运行进程——或者即使这是可行的。我已经阅读了 MSDN 上的各种定义,但我是线程和进程的新手,所以任何对文章的进一步明确引用将不胜感激


这很好...

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

}
}

这不是...

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

为什么第二个和第一个不一样?在第二个脚本中,我尝试使用 Threadstart 委托(delegate)传递 Process.Start ...我认为这可以作为 void 方法吗?第一个脚本是唯一的选择,还是我可以稍微更改第二个脚本,以便它有效地执行与第一个脚本相同的工作,即在指定线程中启动记事本实例?


编辑

关于为什么我在玩这段代码的一些背景知识:最终我需要构建一个将同时运行多个 Excel 进程的应用程序。当 VBA 出错时,这些过程会很麻烦,因为它会导致出现对话框。所以我想如果每个进程都在一个线程中运行,那么如果一个特定的线程已经运行了太长时间,那么我可以终止该线程。我是线程/进程的新手,所以目前基本上是在尝试各种可能性。

最佳答案

ThreadStart 需要一个返回 void 的委托(delegate)。 Process.Start 返回 bool,因此不是兼容的签名。您可以使用为您提供正确返回类型(即 void)委托(delegate)的 lambda 吞下返回值,如下所示:

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

...但最好检查返回值:

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

当然,一个进程是在一个新的进程(完全独立的一堆线程)中启动的,所以在一个线程上启动它是完全没有意义的。

关于c# - 如何在线程中启动进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14455510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com