2017-08-17 112 views
-1

我创建了一个带有2个按钮的WPF应用程序。在执行cmd的第一个按钮的点击并等待命令的完成,因为我需要在执行完成后读取结果文件。在第二个按钮上单击我停止执行cmd进程kill。执行方法时无法与wpf元素进行交互

但是在启动命令执行后,我无法在完成cmd执行之前停止执行。

是否有任何并行执行方式?

开始按钮代码

string filename = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "nunit-console.exe"); 
Process proc = Process.Start(filename, "/result:" + resultFile + ".xml " + fileName); 
proc.WaitForExit(); 
+4

使用[多线程(https://www.tutorialspoint.com/csharp/csharp_multithreading.htm),因为它等待'proc.WaitForExit()你的主线程被冻结;' –

+0

@Nobody是正确的。细化一下,你的UI有它自己的线程,并且需要遵循一些规则来使你的UI更新或更改其他线程。研究异步/等待和更新到/从UI线程。那里有大量的例子和教程。 –

+0

请注意,您可能或可能不需要使用'WaitForExit()'。这取决于其他代码,这是你没有打算展示的。 Process类提供异步处理I/O和状态处理。见例如https://stackoverflow.com/questions/2085778/c-sharp-read-stdout-of-child-process-asynchronously。在后台任务或线程中运行上述代码是最直观的解决问题的方法,但还有其他解决方法。 –

回答

0

只需卸下proc.WaitForExit();。此行阻止接口线程,阻止第二次按钮单击被注册。

System.Diagnostics.Process proc; 

    private void Btn1Click(object sender, RoutedEventArgs e) 
    { 
     string filename = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "nunit-console.exe"); 
     proc = Process.Start(filename, "/result:" + resultFile + ".xml " + fileName); 
    } 

    private void Btn2Click(object sender, RoutedEventArgs e) 
    { 
     if (proc != null) 
      proc.Kill(); 
    } 
相关问题