.NET 11 Preview - Starting A Detached Process
[C#, .NET, .NET 11 Preview]
Yesterday’s post, “.NET 11 Preview - Starting and Forgetting A Process”, looked at how to start and forget a process. Which is to say, a process you want to start but don’t necessarily want to interact with or its results.
A caveat with the Run APIs such as Run, RunAndCaptureText, ReadAllText, ReadAllLines, ReadAllBytes, etc., is that once you terminate the main program, the underlying child process also terminates.
This is generally a good thing, but there are times when you want the child process to outlive its parent.
In this scenario, StartAndForget has an overload that takes a ProcessStartInfo object.
You can use this to specify that you want a detached process as follows:
using System.Diagnostics;
var info = new ProcessStartInfo
{
FileName = "ping",
Arguments = "google.com",
StartDetached = true,
UseShellExecute = false
};
// Start the detached process
Process.StartAndForget(info);
Here, we set the StartDetached property to true.
TLDR
The StartAndForget method has an overload that takes a ProcessStartInfo object you can use to specify a detached process.
The code is in my GitHub.
Happy hacking!