Willi
Willi

Reputation: 361

.Net Core C# Execute method/class as a subprocess

For reasons of memory isolation and stability I need to execute some methods/classes as sub-processes, not threads. I found the following library that allows me to do just that: https://github.com/tmds/Tmds.ExecFunction.

However, I can't seem to find a way to get the process ID of the child process.

ExecFunction.Run(() => new NewSubProcessClass());

The code above will generate a new process and will even generate console output in a Linux Docker container. The problem is, that I have no process ID.

public static Process Start(Action action, Action<ExecFunctionOptions> configure = null);

The method I quoted above looked like it should do the trick, however, when I replace

ExecFunction.Run(() => new NewSubProcessClass());

with

Process process = ExecFunction.Start(() => new NewSubProcessClass());

I no longer get any console output.

UPDATE 0:

The suggestion from @bazzilic

process.WaitForExit();

is the solution to the problem.

Upvotes: 3

Views: 2285

Answers (1)

bazzilic
bazzilic

Reputation: 828

If you examine the source code for Tmds.ExecFunction, both methods .Run(...) (here) and .Start(...) (here) under the hood call the same private method .Start(...) (source here). The two differences are:

  1. the public .Start(...) method returns the process object from the tuple returned by the private .Start(...) method whereas .Run(...) does not;
  2. the .Run(...) method also supplies waitForExit: true in the parameters.

In the code of the private .Start(...) method, there is this portion:

if (waitForExit)
{
    process.WaitForExit();
}

Other than that, the two public methods are identical. The difference in your code behavior is most likely due to not waiting for the child process to finish in your parent process. Try this:

Process process = ExecFunction.Start(() => new NewSubProcessClass());
process.WaitForExit();

PS: Keep in mind that Process is IDisposable, so might be better to do

using ( Process process = ExecFunction.Start(() => new NewSubProcessClass()) ) {
    process.WaitForExit();
}

Upvotes: 1

Related Questions