Process.Start导致我的WPF程序崩溃

本文关键字:WPF 程序 崩溃 我的 Start Process | 更新日期: 2023-09-27 18:27:49

我有一个WPF程序,它在进程中打开Word文档,等待进程完成后再继续。如果我让Word打开几个小时,我的程序就会崩溃。

当进程运行时,我可以看到应用程序的内存在稳步增加。

我尝试了两种方法,但都有相同的记忆力问题。

路#1

public void ShowExternalReference(string externalRef, bool waitForCompletion)
{
    if (!string.IsNullOrEmpty(externalRef))
    {
        using (var p = Process.Start(@externalRef))
        {
            if (waitForCompletion)
            {
                // Wait for the window to finish loading.
                p.WaitForInputIdle();
                // Wait for the process to end.
                p.WaitForExit();
            }
        }
    }
}

2路

public void ShowExternalReference(string externalRef, bool waitForCompletion)
{
    if (!string.IsNullOrEmpty(externalRef))
    {
        using (var p = Process.Start(@externalRef))
        {
            if (waitForCompletion)
            {
                while (!p.HasExited)
                {
                    Thread.Sleep(1000);
                }
            }
        }
    }
}

有什么想法吗?

Process.Start导致我的WPF程序崩溃

我读过评论,很长一段时间以来,WaitForExit()似乎存在内存问题。

所以我会这样做:

  1. 启动进程并仅检索其PID
  2. 定期检查流程是否仍处于活动状态

也许这不会产生同样的记忆问题。

我的建议:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private System.Threading.Timer _timer;
    public MainWindow()
    {
        InitializeComponent();
        this.Content = new TextBlock() { Text = "Close notepad.exe when you want..." };
        // - Launch process
        Process p = Process.Start("notepad.exe");
        int processId = p.Id;
        _timer = new System.Threading.Timer(new System.Threading.TimerCallback(o => CheckPID((int)o)), processId, 0, 1000);
    }
    /// <summary>
    /// Check if Process has exited
    /// </summary>
    /// <remarks>This code is NOT in UI Thread</remarks>
    /// <param name="processId">Process unique ID</param>
    private void CheckPID(int processId)
    {
        bool stillExists = false;
        //Process p = Process.GetProcessById(processId); // - Raises an ArgumentException if process has alredy exited
        Process p = Process.GetProcesses().FirstOrDefault(ps => ps.Id == processId);
        if (p != null)
        {
            if (!p.HasExited)
                stillExists = true;
        }
        // - If process has exited, do remaining work and stop timer
        if (!stillExists)
        {
            _timer.Dispose();
            // - Ask UI thread to execute the final method
            Dispatcher.BeginInvoke(new Action(ExternalProcessEnd), null);
        }
    }

    /// <summary>
    /// The external process is terminated
    /// </summary>
    /// <remarks>Executed in UI Thread</remarks>
    private void ExternalProcessEnd()
    {
        MessageBox.Show("Process has ended");
    }
}

缺点是我们将无法检索StandardOutput、StandardError和ExitStatus。