Luc*_*uca 7 c# process sta blocking
我正在调用Process.Start,但它会阻止当前线程.
pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");
// Start process
mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
Trace.TraceError("Unable to run process {0}.");
}
Run Code Online (Sandbox Code Playgroud)
即使进程关闭,代码也不再响应.
但是Process.Start真的应该阻止吗?这是怎么回事?
(流程正确启动)
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace Test
{
class Test
{
[STAThread]
public static void Main()
{
Thread ServerThread = new Thread(AccepterThread);
ServerThread.Start();
Console.WriteLine (" --- Press ENTER to stop service ---");
while (Console.Read() < 0) { Application.DoEvents(); }
Console.WriteLine("Done.");
}
public static void AccepterThread(object data)
{
bool accepted = false;
while (true) {
if (accepted == false) {
Thread hThread = new Thread(HandlerThread);
accepted = true;
hThread.Start();
} else
Thread.Sleep(100);
}
}
public static void HandlerThread(object data)
{
ProcessStartInfo pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");
Console.WriteLine("Starting process.");
// Start process
Process mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
Console.WriteLine("Unable to run process.");
}
Console.WriteLine("Still living...");
}
}
}
Run Code Online (Sandbox Code Playgroud)
控制台输出是:
---按ENTER键停止服务---启动过程.
找到了:
[STAThread]
使Process.Start阻塞.我读过STAThread和多线程,但我无法将这些概念与Process.Start行为联系起来.
Windows.Form 需要 AFAIK,STAThread .如何在使用Windows.Form时解决此问题?
地狱新闻:
如果我重建我的应用程序,第一次正确运行应用程序工作,但如果我停止调试并重新启动iy,问题就出现了问题.
在没有调试器的情况下执行应用程序时,不会引发此问题.
Jon*_*eet 12
不,Process.Start不等待子进程完成...否则您将无法使用重定向I/O等功能.
示例控制台应用:
using System;
using System.Diagnostics;
public class Test
{
static void Main()
{
Process p = new Process {
StartInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe")
};
p.Start();
Console.WriteLine("See, I'm still running");
}
}
Run Code Online (Sandbox Code Playgroud)
这打印"看,我还在跑",我的盒子上没有任何问题 - 它在盒子上做了什么?
小智 7
创建ProcessStartInfo并将UseShellExecute设置为false(默认值为true).您的代码应为:
pInfo = new ProcessStartInfo("C:\\Windows\\notepad.exe");
pInfo.UseShellExecute = false;
// Start process
mProcess = new Process();
mProcess.StartInfo = pInfo;
if (mProcess.Start() == false) {
Trace.TraceError("Unable to run process {0}.");
}
Run Code Online (Sandbox Code Playgroud)
我有同样的问题,并启动可执行文件直接从可执行文件创建过程解决了问题.
| 归档时间: |
|
| 查看次数: |
12211 次 |
| 最近记录: |