A long-running C# process on stdin and stdout

The second way keeps the process. The same program that prices one line from its arguments can also read a line at a time from standard input, answer it and wait for the next one. A caller that starts it once and writes to its standard input pays the runtime start once and then a fraction of a millisecond per request.

The CLI project

The host is a console project with a ProjectReference to the core, which is the same pair the class library lesson builds:

<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\Core\Core.csproj" /> </ItemGroup> </Project>

The loop

Two modes in one program: --daemon reads until the end of the input and answers every line; without it the program takes the line from its arguments, or from the whole of standard input. The last statement of the one-shot mode is at the top level, so the file is a whole program:

using Core; if (args.Length > 0 && args[0] == "--daemon") { string? line; while ((line = Console.ReadLine()) is not null) { Console.WriteLine(Pricing.Process(line)); } return 0; } var input = args.Length > 0 ? string.Join(' ', args) : Console.In.ReadToEnd().Trim(); Console.WriteLine(Pricing.Process(input)); return 0;

Console.ReadLine returns null at the end of the input, which is the loop condition. The write of each answer ends with a line break, which is the whole framing of the protocol: one request is one line and one answer is one line, so the caller can read one answer per request without a length prefix.

The run

A pipe is enough to show the mode: three lines in, three lines out, one process:

printf "sku=pen qty=2 unit=1.50\nsku=paper qty=10 unit=0.25\nsku=pen qty=0 unit=1.50\n" | dotnet src/Cli/bin/Release/net10.0/Cli.dll --daemon
echo "status: $?"

ok 3.00 0.60 3.60
ok 2.50 0.50 3.00
err qty must be 1 to 100
status: 0

The status is zero after the last line, because the end of the input is the normal end of the daemon. A client that wants to keep the process for many requests holds it open and writes a line for each one, which is what the Python client of the timing page does:

The client

The client starts the process once with subprocess.Popen, keeps its standard input and output open, and for each request writes a line, flushes it and reads one line. The flush is the part that matters: without it the line may sit in the pipe buffer and the daemon waits for an input that the client thinks it sent.

#!/usr/bin/env python3 """Three ways to call the C# pricing core, and a timing of each.""" import json import statistics import subprocess import sys import time import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parent.parent CLI = ROOT / "src" / "Cli" / "bin" / "Release" / "net10.0" / "Cli.dll" API = "http://127.0.0.1:5099/price" LINE = "sku=pen qty=2 unit=1.50" def by_process(line): result = subprocess.run( ["dotnet", str(CLI), line], capture_output=True, text=True, check=False, timeout=10, ) return result.stdout.strip() class Daemon: def __init__(self): self.process = subprocess.Popen( ["dotnet", str(CLI), "--daemon"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1, ) def price(self, line): self.process.stdin.write(line + "\n") self.process.stdin.flush() return self.process.stdout.readline().strip() def close(self): self.process.stdin.close() self.process.wait(timeout=10) def by_api(line): request = urllib.request.Request(API, data=line.encode(), method="POST") with urllib.request.urlopen(request) as response: return response.read().decode() def measure(name, call, runs, calls): times = [] for _ in range(runs): start = time.perf_counter() for _ in range(calls): call(LINE) times.append((time.perf_counter() - start) / calls * 1000) ordered = sorted(times) print( f"{name}: min {ordered[0]:.3f} ms median {ordered[len(ordered) // 2]:.3f} ms " f"runs " + " ".join(f"{time:.3f}" for time in times) ) def demo(): print("process", by_process(LINE)) daemon = Daemon() try: print("daemon ", daemon.price(LINE)) print("daemon ", daemon.price("sku=paper qty=10 unit=0.25")) finally: daemon.close() print("api ", by_api(LINE)) def timing(runs, calls): daemon = Daemon() try: measure("process", by_process, runs, calls) measure("daemon ", daemon.price, runs, calls) measure("api ", by_api, runs, calls) finally: daemon.close() if __name__ == "__main__": command = sys.argv[1] if len(sys.argv) > 1 else "demo" if command == "timing": timing(int(sys.argv[2]) if len(sys.argv) > 2 else 5, int(sys.argv[3]) if len(sys.argv) > 3 else 20) else: demo()

The next page gives the same core an HTTP address, with the web SDK and a minimal API.

Exercises

  1. Add a quit line that ends the daemon before the end of the input.
  2. Add a request id to the protocol and echo it in the answer.
  3. Make the client restart the daemon when an answer is empty.
  4. Measure the daemon through the client with the timing page and compare it with the API.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What ends the daemon loop?

    Answer

    The end of the input, which gives ReadLine a null

    The loop condition is a null from ReadLine.

  2. Why must the client flush after writing a line?

    Answer

    The line may stay in the pipe buffer and the daemon never sees it

    The page names the deadlock that a missing flush causes.

  3. What does this program print? Console.WriteLine("ok 3.00 0.60 3.60");

    Answer

    ok 3.00 0.60 3.60

    That is the first answer of the measured daemon run.

  4. How many processes does the daemon way use for three requests?

    Answer

    One

    The whole point of the mode is one process for many lines.

  5. What does this program print? var lines = new[] { "a", "b", "c" }; Console.WriteLine(lines.Length);

    Answer

    3

    The pipe carried three lines and the daemon answered three.

  6. What is the framing of this protocol?

    Answer

    One request is one line and one answer is one line

    The page explains why a line needs no length prefix.

  7. What does this program print? Console.WriteLine("err qty must be 1 to 100");

    Answer

    err qty must be 1 to 100

    The third line of the measured run is the invalid quantity.

  8. What does a crashing daemon leave the client with?

    Answer

    An empty line and no error, so the client must check the answer

    The page says a real client validates and restarts.

  9. What is the clean shutdown of the daemon?

    Answer

    Closing its standard input

    The loop ends and the process exits with zero.

  10. What does this program print? string? line = ""; Console.WriteLine(line is not null);

    Answer

    True

    An empty string is not a null, which is the difference the loop handles.

The C# code on this page was built with the .NET SDK 10.0.303 and the Python code was run with Python 3.14.10, on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev