gpt4 book ai didi

c# - 使用外部进程卡住UI

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:51 24 4
gpt4 key购买 nike

我已经实现了以下代码(从tutorial改编而成),以便运行命令提示符窗口,运行程序并读取输出。从嵌套在用户控件中的ButtonClick事件处理程序调用该代码。

我的印象是,由于方法是“异步的”,因此这将允许程序的其余部分在外部进程运行时运行。但是,情况似乎并非如此,因为在运行操作时,我的UI会冻结。我应该补充一点,cmd进程结束时收到的输出是正确的。

很抱歉,这样的代码转储,只是不确定现在还要做些什么!

任何帮助将不胜感激。

public static void runExternalProcess()
{
StringBuilder output = new StringBuilder();

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardOutput = true;

cmd.OutputDataReceived += new DataReceivedEventHandler(outputEventHandler);
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
cmd.BeginOutputReadLine();

StreamWriter sortStreamWriter = cmd.StandardInput;
StreamWriter sw = cmd.StandardInput;

if (sw.BaseStream.CanWrite)
{
sw.WriteLine("ping www.google.com");
}

sw.Close();

cmd.WaitForExit();

MessageBox.Show(output.ToString());

cmd.Close();
}

private static void outputEventHandler(object sendingProcess, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
output.Append(e.Data + Environment.NewLine);
}
}

最佳答案

如何注册Exited事件并在其中显示MessageBox

StringBuilder output = new StringBuilder();
Process cmd = new Process();

public void RunExternalPing()
{
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.RedirectStandardInput = true;

cmd.EnableRaisingEvents = true;
cmd.OutputDataReceived +=
new DataReceivedEventHandler(cmd_OutputDataReceived);
cmd.Exited += new EventHandler(cmd_Exited);

cmd.Start();
cmd.BeginOutputReadLine();
StreamWriter sw = cmd.StandardInput;
sw.WriteLine("ping www.google.com");
sw.Close();
}

void cmd_Exited(object sender, EventArgs e)
{
MessageBox.Show(output.ToString());
cmd.Dispose();
}

private void cmd_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
output.Append(e.Data + Environment.NewLine);
}
}


从MSDN:


  关联过程有两种通知方式
  退出:同步和异步。同步通知
  依赖于调用WaitForExit方法来暂停处理
  您的应用程序,直到关联的组件退出。异步
  通知依赖于Exited事件。在任一情况下,
  必须将EnableRaisingEvents设置为true,Process组件才能
  收到有关进程已退出的通知。

关于c# - 使用外部进程卡住UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10127143/

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