【问题标题】:Process.Start() returns null on own processProcess.Start() 在自己的进程上返回 null
【发布时间】:2010-10-18 04:30:57
【问题描述】:

我正在使用 Process.Start() 来初始化当前运行的应用程序的提升副本。不幸的是 Process.Start() 返回 null 因为它认为它正在使用我的应用程序的现有进程,并且虽然存在现有进程,但它没有指定任何处理此类入口点的方式。

.NET 中是否有任何方法(通过配置或其他方式)我可以告诉系统不要重用我的进程的现有副本?这个问题似乎只发生在 Windows XP 上,而不是 Vista 或 7。

代码副本如下:

internal static bool EnsureAssociation()
{
    // Check to make sure RoketPack is associated.
    if (!Protocol.IsAssociated())
    {
        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = UNC.UniversalApplicationPath;
        info.UseShellExecute = true;
        if (!UAC.IsAdmin())
            info.Verb = "runas"; // Provides Run as Administrator
        info.Arguments = "--associate";
        Process proc = null;
        try
        {
            proc = Process.Start(info);
        }
        catch (Win32Exception)
        {
            Errors.Raise(Errors.ErrorType.ERROR_CAN_NOT_ASSOCIATE_PROTOCOL);
            return false;
        }

        if (null != proc)
        {
            // Wait until the association is complete.
            proc.WaitForExit();
            return Protocol.IsAssociated();
        }
        else
        {
            Errors.Raise(Errors.ErrorType.ERROR_CAN_NOT_ASSOCIATE_PROTOCOL);
            return false;
        }
    }
    else
        return true;
}

【问题讨论】:

    标签: .net process null


    【解决方案1】:

    我通过检查 UAC.IsAdmin() 是否为真解决了这个问题,如果是,只需执行提升的进程会执行的操作。

    这并不能直接解决 Process.Start() 返回 null 的问题,但我认为造成重用的情况是因为本来应该启动的进程在各方面都是相同的(哪里好像进程通过'runas'动词开始提升,它被认为是不同的并且不会返回null)。

    【讨论】:

      【解决方案2】:

      您要做的是默认行为,即任何程序都可以运行多个实例。阻止应用程序多次运行需要额外的代码。

      查看ReflectorProcess.Start()

      public static Process Start(ProcessStartInfo startInfo)
      {
          Process process = new Process();
          if (startInfo == null)
          {
              throw new ArgumentNullException("startInfo");
          }
          process.StartInfo = startInfo;
          if (process.Start())
          {
              return process;
          }
          return null;
      }
      

      您可以追踪返回 null 的位置。如果进程无法在process.Start() 内启动,它将返回null

      public bool Start()
      {
          this.Close();
          ProcessStartInfo startInfo = this.StartInfo;
          if (startInfo.FileName.Length == 0)
          {
              throw new InvalidOperationException(SR.GetString("FileNameMissing"));
          }
          if (startInfo.UseShellExecute)
          {
              return this.StartWithShellExecuteEx(startInfo);
          }
          return this.StartWithCreateProcess(startInfo);
      }
      

      ...

      你明白了。继续追踪您获得null 值的原因。如果您还没有 Reflector 的副本,立即获取!

      NB:很抱歉,这并没有为您的问题提供确切的解决方案,但它表明您可以自己去寻找它。 :)

      HTH,

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-10
        • 2017-08-31
        • 1970-01-01
        • 2018-01-10
        • 2017-06-15
        • 1970-01-01
        相关资源
        最近更新 更多