进一步编辑 以下不是生产代码 - 我只是在试图弄清楚如何在线程中运行进程 - 或者即使这是可行的.我已经在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();
}
}
Run Code Online (Sandbox Code Playgroud)
这不是......
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();
}
}
Run Code Online (Sandbox Code Playgroud)
为什么第二个与第一个不一样?在第二个脚本中,我试图Process.Start使用Threadstart委托传递...我认为这可以作为一个void方法吗?第一个脚本是唯一的选项,还是可以稍微更改第二个脚本,以便它有效地执行与第一个相同的工作,即在指定的线程中启动记事本的实例?
编辑
关于为什么我要使用这段代码的一些背景知识:最终我需要构建一个同时运行多个Excel进程的应用程序.当VBA错误导致对话框时,这些过程可能会很麻烦.所以我想如果每个进程都在一个线程中运行,那么如果一个特定的线程已经运行了太长时间,那么我可以杀死该线程.我是Threads/Processes的新手,所以基本上可以玩弄当前的可能性.
spe*_*der 25
ThreadStart需要一个返回void的委托.Process.Start返回bool,因此不是兼容的签名.您可以通过使用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();
Run Code Online (Sandbox Code Playgroud)
...但是检查返回值可能是明智的:
ThreadStart ths = new ThreadStart(() => {
bool ret = pr.Start();
//is ret what you expect it to be....
});
Run Code Online (Sandbox Code Playgroud)
当然,一个进程在一个新进程(一组完全独立的线程)中启动,因此在一个线程上启动它是完全没有意义的.
你可以做出改变
ThreadStart ths = new ThreadStart(delegate() { pr.Start(); });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42982 次 |
| 最近记录: |