Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Executing .NET Core functions in a separate process

July 17, 2019
Tom Deseyn
Related topics:
.NET

    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

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.