Process.Start 启动进程,但返回 null



我有一个Windows表单应用程序,它做一件事:启动Edge,杀死进程:

private void Form1_Load(object sender, EventArgs e)
{
try
{
Process edgeProc = new Process();
edgeProc = Process.Start("microsoft-edge:.exe");
edgeProc.Kill();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
}
}

我没有一台装有 Win10 + Edge 的计算机来调试此代码,但我间接可以访问 Windows 10 VM。我构建了我的应用程序并在该虚拟机上运行 exe,Edge 启动,但随后抛出异常:

对象引用未设置为对象的实例。

at EdgeLauncher.Form1.Form1_Load(Object sender, EventArgs e)

我了解什么是NullReferenceException,并且对这个问题非常熟悉。

MSDN 说:

与进程资源

关联的新进程,如果未启动进程资源,则为 null。

Edge正在启动,因此不应edgeProcessnull。那么为什么我会收到此错误?

你正在使用 shell 来执行该命令。不能保证与此相关的过程。仅仅因为出现一个新窗口并不意味着一个新进程已经启动:)

如果您总是想开始一个新过程,请不要使用UseShellExecute- 不用说,这本身就有复杂性。

new Process()在这个用例中是无用的。你可以做:

private void Form1_Load(object sender, EventArgs e)
{
try
{
Process edgeProc = Process.Start("microsoft-edge:.exe");
edgeProc?.Kill(); // the "?." will prevent the NullReferenceException 
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + Environment.NewLine +    Environment.NewLine + ex.StackTrace);
}
}

如果未启动进程,则Process.Start(...)返回null

最新更新