0

I have a simple WPF application with a button, when the button clicked it calls to a method that start a process - cmd command, the cmd command can take 1 minute. The problem is, at this time (when the process wait for exit and get a result) the application is stuck.

My code in the UI is:

private void Button_Click(object sender, RoutedEventArgs e)
{
    // the method Import take 1 minute
    var result = Helpers.Import();
    if (result)
    {
    MessageBox.Show("Sucess", "Sucess");
    }
    else
    {
    MessageBox.Show("Error", "Error",);
    }
}

My code in the BL is:

public static bool Import()
{
    ProcessStartInfo info = new ProcessStartInfo(@"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\witadmin.exe", arguments);
    info.CreateNoWindow = true;
    info.WindowStyle = ProcessWindowStyle.Hidden;
    Process p = Process.Start(info);
    p.WaitForExit();

    if (p.ExitCode == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

When the application waits for the exit code the UI is stuck.

How can I solve it?

Shayki Abramczyk
  • 36,824
  • 16
  • 89
  • 114
  • 3
    Possible duplicate of [process.WaitForExit() asynchronously](https://stackoverflow.com/questions/470256/process-waitforexit-asynchronously) – FakeCaleb Jul 30 '18 at 08:26
  • Don't call `WaitForExit` in UI thread. You can create a new task and `await` for it. Consider adding more code (ideally [mcve](https://stackoverflow.com/help/mcve)), so that someone can quickly make it asynchronous. – Sinatr Jul 30 '18 at 08:44
  • @FakeCaleb I tried the answers there but without success, I added more code to my question. – Shayki Abramczyk Jul 30 '18 at 10:23
  • @ShaykiAbramczyk the answers on the post should work, I recommend updating your question with your attempted implementation of those answers to see the issue – FakeCaleb Jul 30 '18 at 10:28

2 Answers2

1

I solved in like @Sinatr's comment, I made the method Button_Click async, and open a new Task.

private async void Button_Click(object sender, RoutedEventArgs e)
{
   bool result = false;
   await Task.Run(() =>
   {
       import = Helpers.Import();
   });
   if (result)
   {
       MessageBox.Show("Sucess", "Sucess");
   }
   else
   {
       MessageBox.Show("Error", "Error",);
   }
}
Shayki Abramczyk
  • 36,824
  • 16
  • 89
  • 114
0

method WaitForExit() -> instructs the Process component to wait an infinite amount of time for the process and event handlers to exit. This can cause an application to stop responding.

LuFFy
  • 8,799
  • 10
  • 41
  • 59