loading experience

.NET

.NET 11 libraries: processes, compression, numbers and in-memory streams

A guide to the .NET 11 libraries: Process, Zstandard, ZIP, Base64, Decimal32/64/128, Complex<T>, generic Random, in-memory streams and BitArray.

.NET 11 is generally available, and the base libraries grow in many directions. This first article collects what is new for process execution, text, compression and archives, numerics, in-memory streams, low-level I/O and collections. The sections come from the official libraries page; the rest (JSON, networking, cryptography, diagnostics) is in the second article of the series.

Process: running and capturing output

The Process class gets a large set of APIs for scenarios that used to need OutputDataReceived/ErrorDataReceived events or P/Invoke.

ProcessTextOutput result = await Process.RunAndCaptureTextAsync(
    "git", ["status", "--porcelain"]);
Console.WriteLine(result.StandardOutput);
Console.WriteLine($"Exit code: {result.ExitStatus.ExitCode}");
  • Run and capture: Process.Run/RunAsync, RunAndCaptureText/RunAndCaptureTextAsync, ReadAllText, ReadAllBytes (plus async variants), ReadAllLines and ReadAllLinesAsync, which tell stdout from stderr through ProcessOutputLine.
  • Fire and forget: Process.StartAndForget, ProcessStartInfo.StartDetached (the child can outlive a terminal exit) and KillOnParentExit (Windows only).
  • SafeProcessHandle: Start, the ProcessId property, Kill(), Signal(PosixSignal), WaitForExit() and WaitForExitAsync.
  • Handle control: InheritedHandles, and StandardInputHandle/StandardOutputHandle/StandardErrorHandle taking already-open SafeFileHandle values.
  • Suspended start and lookup: StartSuspended (Windows and macOS) paired with SafeProcessHandle.Resume(); Process.TryGetProcessById, Open and TryOpen.
  • Signals and exit status: Process.Signal(PosixSignal), WaitForExitStatus, TryWaitForExitStatus and WaitForExitStatusAsync return a ProcessExitStatus that separates a normal exit from a signal-based termination.

The console also honors the FORCE_COLOR standard next to NO_COLOR: when set, Console.IsOutputRedirected no longer suppresses ANSI escape codes (handy with tee, CI log viewers or less -R). On Windows, Process uses overlapped I/O for redirected stdout/stderr, which reduces thread-pool blocking.

Streams over in-memory data

Four new Stream types wrap in-memory data without copying it into a MemoryStream:

  • ReadOnlyMemoryStream, a read-only stream over ReadOnlyMemory<byte>;
  • WritableMemoryStream, a fixed-size stream over Memory<byte>;
  • ReadOnlySequenceStream, over ReadOnlySequence<byte> (for example from System.IO.Pipelines) without flattening segments;
  • StringStream, which reads a string or ReadOnlyMemory<char> with a chosen encoding.

Text, Base64 and UTF validation

  • Runes: String accepts Rune in Contains, StartsWith, EndsWith, IndexOf, LastIndexOf, Replace, Split, Trim, TrimStart, TrimEnd, with many StringComparison overloads; TextInfo adds ToLower(Rune) and ToUpper(Rune); Char.Equals(Char, StringComparison) is new.
  • StringBuilder.MoveChunks: moves content into a new StringBuilder without copying characters; the source ends at length 0.
  • Base64: EncodeToChars, EncodeToString, EncodeToUtf8, DecodeFromChars, DecodeFromUtf8, both convenient and span-based.
  • UTF: Utf16.IsValid, Utf8.IndexOfInvalidSubsequence and Utf16.IndexOfInvalidSubsequence (position of the first error, or -1) allow precise error reporting.
  • Regex: RegexOptions.AnyNewLine makes ^, $ and . treat all Unicode newlines as line terminators; the non-backtracking engine avoids super-linear time on certain nested loops, and the compiler and source generator fix conditionals inside loops and duplicate class names (SYSLIB1045).

Compression and archives

  • Zstandard: ZstandardStream and ZstandardEncoder move into the System.IO.Compression namespace; ZstandardDictionary.Train and Create handle dictionaries.
  • ZIP: ZipArchiveEntry.Open(FileAccess) and OpenAsync; a CompressionMethod property (Stored, Deflate, Deflate64); password-protected entries with ZipEncryptionMethod.
  • CRC32 validation: corrupted or truncated archives that used to pass now throw InvalidDataException.
  • DeflateStream and GZipStream: always write headers and footers, even with no data, so the output is a valid stream per the specifications (a behavior change).
  • Span-based APIs: DeflateEncoder, ZLibEncoder, GZipEncoder and their decoders compress and decompress buffers without a Stream, with a Reset() method for reuse.
  • Tar: CreateFromDirectory/CreateFromDirectoryAsync overloads take a TarEntryFormat (Pax, Ustar, GNU, V7); TarReader also reads the GNU sparse 1.0 format.

Numbers and math

  • Decimal32, Decimal64, Decimal128: in System.Numerics, with IEEE 754-2019 semantics, generic math, infinities and NaN. Transcendental functions are more accurate (for example Decimal128.Acos(1 - 1e-30) used to be far off and is now well under one ULP); because results change, last digits compared with stored values may differ.
  • Correctly rounded conversions: from Decimal and BigInteger to binary floating-point types, with a single rounding; there is no switch to restore the old algorithms. Converting the double literal 1.23 no longer yields 1.23, so use 1.23m when the value is meant to be decimal.
  • TryParsePartial: INumberBase<TSelf>.TryParsePartial reports how much input was consumed, useful for CSV without substrings.
  • Complex<T>: complex arithmetic over float, Half, BFloat16 and the new decimal types.
  • BFloat16 in BitConverter: GetBytes, ToBFloat16 and bit conversions.
  • IEEE-754 hex form: double, float and Half format and parse as hexadecimal (ToString("X"), NumberStyles.HexFloat) with an exact round trip.
  • Generic Random: Random.NextInteger<T> and Random.NextBinaryFloat<T>.
  • Vectors: Vector64/128/256/512<T> and Vector<T> add patterned construction (CreateGeometricSequence, CreateAlternatingSequence, CreateHarmonicSequence), Zip/Unzip, the Concat family and Reverse.
  • Matrix4x4.GetDeterminant(): SSE-vectorized, about 15% faster.

Low-level I/O

  • SafeFileHandle.Type tells whether a handle is a file, pipe, socket or directory; SafeFileHandle.CreateAnonymousPipe creates connected pipe handles with independent async behavior per end.
  • RandomAccess.Read and Write now work with non-seekable handles such as pipes.
  • On iOS and tvOS, FileStream no longer takes advisory locks by default (FileShare restrictions are not enforced); restore it with System.IO.DisableFileLocking set to false or DOTNET_SYSTEM_IO_DISABLEFILELOCKING=0.

Collections and Tensors

  • BitArray: constructors from ReadOnlySpan<bool>, <byte>, <int>, and a PopCount() method.
  • EqualityComparer<T>.Create: builds a comparer from a key selector.
  • ConcurrentQueue<T>: TryDequeue and TryPeek no longer report an empty queue by mistake while it grows.
  • System.Numerics.Tensors: updating the package changes shape alignment and rejects unsupported overlapping storage layouts, even on frameworks older than .NET 11: review code that relies on particular shapes or overlapping copies.

Developer platform

  • Discriminated-union scaffolding: UnionAttribute and IUnion, not yet meant for direct use.
  • MetadataLoadContext.GetLoadContext, Type.GetNullableUnderlyingType(), ConstructorInfo.GetGenericArguments(), AssemblyLoadContext.SetAssemblyLocationOverride, Uri.UriSchemeData, and StringSyntax constants for C#, F# and Visual Basic.
  • System.IO.Pipelines reduces reader and writer contention under high fan-in.

The rest is in the article on JSON, networking and security; for command-line tooling see the SDK article.

Sources

Comments (0)

No comments yet.

Leave a comment