Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

Executing .NET Core functions in a separate process

July 17, 2019
Tom Deseyn
Related topics:
.NET

Share:

    In this article, we'll take a look at Tmds.ExecFunction, which is a library that allows developers to easily execute a .NET Core function in a separate process.

    Use cases

    Before we get to the code, let's cover a few scenarios where it makes sense to execute a function as a separate process. Processes have some global state, like environment variables and the working directory. Most of the time, this global state doesn't cause issues: When it is meaningful, libraries provide an API that allows the user to override the values. For testing, though, it's a different story. To verify the application is properly using the global state as a default, we need to modify it. This factor is an issue because the state is shared with the test host process and the other tests running in that process. We can solve this issue by running code in a separate process that we can fully control.

    The second class of use cases occurs when we want code to run with a different lifetime from the parent process. For example, suppose we want to start a process and ensure it doesn't outlive the .NET parent (even on crashes). We could do this by putting a small process in between that monitors the parent, and kills the child when the parent has terminated. Another example is to implement double forking, which is used in script-based init managers to make sure the daemon outlives the shell that launched it. Most distributions (like Fedora and Red Hat Enterprise Linux) are now using systemd as their init manager, which doesn't need daemons to double fork.

    Tmds.ExecFunction

    Tmds.ExecFunction is a library inspired by .NET Core's RemoteExecutor, which is used in .NET Core's class library for writing tests that need a separate process. This library is available on NuGet.org, so we can add it to our project using:

    dotnet add package Tmds.ExecFunction

    Now, let's use it:

    ExecFunction.Run(() => Console.WriteLine("Hello world!"));

    We are using ExecFunction.Run and passing it a lambda that prints Hello world! That lambda is executed in a separate process. The Run method then returns when the child has terminated. ExecFunction also provides a Start method that returns a System.Diagnostics.Process and then returns immediately when the process starts. A RunAsync method is also provided, which returns a Task that completes when the process terminates.

    The function we pass can have a .NET Main signature: a void/string[] argument and a void/int/Task/Task return type.

    For example, we can pass some arguments:

    ExecFunction.Run(
        (string[] args) => Console.WriteLine($"Hello {args[0]}"),
        new string[] { "world!" });
    

    We can also control the environment variables, working directory, etc. by passing a configuration function:

    ExecFunction.Run(
        () => Console.WriteLine($"HOME={Environment.GetEnvironmentVariable("HOME")}"),
        o => o.StartInfo.Environment["HOME"] = "/tmp");
    

    The FunctionExecutor class makes it easy to reuse the same configuration for multiple invocations, as well. For example, we can use it as follows in xUnit tests:

    private FunctionExecutor Executor = new FunctionExecutor(
        o =>
        {
                o.StartInfo.RedirectStandardError = true;
                o.OnExit = p =>
                {
                        if (p.ExitCode != 0)
                        {
                    string message = $"Function execution failed with exit code: {p.ExitCode}" + Environment.NewLine +
                                    p.StandardError.ReadToEnd();
                    throw new Xunit.Sdk.XunitException(message);
                        }
                };
        });
    
    [Fact]
    public void Test()
    {
        Executor.Run(
            () =>
            {
                    Assert.Equal("/tmp", Environment.GetEnvironmentVariable("HOME"));
            },
            o => o.StartInfo.Environment["HOME"] = "/tmp"
        );
    }
    

    So far, we’ve been assuming you use the dotnet executable to host your application; for example, by starting xUnit tests using dotnet test. To make ExecuteFunction work from an application host (that is, you built your application into a native binary), we need to add a hook in the Main function:

    static int Main(string[] args)
    {
        if (ExecFunction.IsExecFunctionCommand(args))
        {
                return ExecFunction.Program.Main(args);
        }
        else
        {
                ExecFunction.Run(() => System.Console.WriteLine("Hello world!"));
                return 0;
        }
    }
    

    Conclusion

    In this article, we've shown how to execute .NET Core code easily in a separate process using Tmds.ExecFunction, and when doing so can be useful. Now, explore what you can make this library do.

    Last updated: September 3, 2019

    Recent Posts

    • How to deploy language models with Red Hat OpenShift AI

    • AI search with style: Fashion on OpenShift AI with EDB

    • What qualifies for Red Hat Developer Subscription for Teams?

    • How to run OpenAI's gpt-oss models locally with RamaLama

    • Using DNS over TLS in OpenShift to secure communications

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue