anotheruser
anotheruser

Reputation: 51

How to always run new instance of a process in C#?

Based on this https://msdn.microsoft.com/en-us/library/53ezey2s(v=vs.110).aspx Process.Start() is not useful.

Start may return a non-null Process with its HasExited property already set to true. In this case, the started process may have activated an existing instance of itself and then exited.

In my case, I want to launch a default editor for a xml in new instance so that i can use Process.HasExited property to take action on my WPF app. All i see is native samples or way complicated than thought. What is the best solution ?

Process process = Process.Start(MyFileXMlPath);
//Wait for the Editor to be closed.
if (process != null) 
    while (!process.HasExited) ;

This is what i have now. So that i uses the user's preferred editor.

Upvotes: 1

Views: 808

Answers (1)

Chris Shain
Chris Shain

Reputation: 51319

What's going on is expected behavior- the editor is being asked to open a file, and it is opening that file in an existing running process. One solution might be to use Process.GetProcesses to get all of the running processes on the box and iterate over them to find the new one, but that's likely problematic, because there is really no good way to tell which one opened the file.

What you probably want to do is to set UseShellExecute to false, run the editor you want explicitly (e.g. @"c:\Windows\notepad.exe") and pass the file name as a parameter, which is usually the convention to open a file. Obviously you'd want to pick an editor that doesn't invoke an existing instance.

Upvotes: 1

Related Questions