gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:46:10 25 4
gpt4 key购买 nike

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

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

我尝试了 2 种方法来执行此操作,但都存在相同的内存问题。

方式#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);
}
}
}
}
}

有什么想法吗?

最佳答案

看了评论,好像是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。

关于c# - Process.Start 导致我的 WPF 程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26540331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com