从不同进程更新 UI 失败

发布于 2024-07-18 17:47:24 字数 982 浏览 5 评论 0原文

我正在尝试将 nmap 的标准输出放入 WPF 窗口应用程序(确切地说是文本框)。 我正在尝试使用 Dispatcher.Invoke,但是当 nmap 进程启动时,一切都会冻结。 当我在控制台应用程序(没有 Invoke)中尝试此操作时,一切正常,我认为这是 Invoke 方法的问题。 Nmap 本身正在工作,并且正在完成它的工作,但我的窗口中没有任何响应。

这是我正在使用的代码:

 Process nmap = new Process();

 nmap.StartInfo.FileName = Properties.Settings.Default.NmapResidentialPath;
 nmap.StartInfo.Arguments = arguments.ToString();
 nmap.StartInfo.UseShellExecute = false;
 nmap.StartInfo.RedirectStandardOutput = true;
 nmap.OutputDataReceived += new DataReceivedEventHandler(nmap_OutputDataReceived);
 nmap.Start();
 nmap.BeginOutputReadLine();

 nmap.WaitForExit();
 nmap.Close();

以及事件处理程序方法:

void nmap_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Data))
            {
                this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => nmapOutput.Text += "\n" + e.Data));
            }
        }

I'm trying to put standard output from nmap into WPF window application (textbox exactly). I'm trying to use Dispatcher.Invoke but when nmap process starts everything just freezes. When I tried this in a console application (w/o Invoke), everything worked just fine, I think it's a problem with the Invoke method. Nmap itself is working, and finishing it work, but there is no response in my window.

Here's the code I'm using:

 Process nmap = new Process();

 nmap.StartInfo.FileName = Properties.Settings.Default.NmapResidentialPath;
 nmap.StartInfo.Arguments = arguments.ToString();
 nmap.StartInfo.UseShellExecute = false;
 nmap.StartInfo.RedirectStandardOutput = true;
 nmap.OutputDataReceived += new DataReceivedEventHandler(nmap_OutputDataReceived);
 nmap.Start();
 nmap.BeginOutputReadLine();

 nmap.WaitForExit();
 nmap.Close();

And the event handler method:

void nmap_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!String.IsNullOrEmpty(e.Data))
            {
                this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => nmapOutput.Text += "\n" + e.Data));
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼泪淡了忧伤 2024-07-25 17:47:24

这可能是由多种原因造成的。
首先,确保在 UI 线程上创建 nmapOutput 控件。
其次,Dispatcher.Invoke 可能会导致 UI 线程死锁(这可能就是您的情况)。

始终在调用 Invoke 之前调用 Dispatcher.CheckAccess(),或使用 BeginInvoke 以异步方式执行此操作。

This may be caused by various reasons.
First, Ensure that nmapOutput control is created on UI Thread.
Second, Dispatcher.Invoke may cause UI Thread deadlock (and it probably is in your case).

Always call Dispatcher.CheckAccess() before calling Invoke, or use BeginInvoke to perform this operation in async manner.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文