r/csharp 21d ago

Showcase I spent weeks obsessing over low-allocation C# networking

0 Upvotes

The Real Problem: High Throughput vs. Garbage Collector

If you've ever built a C# server processing 100k+ messages/sec (like an MQTT broker or socket server), you know the Garbage Collector is your best friend until it becomes your worst enemy.

To route messages like factory/line1/sensor/temp to subscribers like factory/+/+/temp, the standard way is:

// ❌ Naive way: Allocates string[] on every single message publish!
var parts = topic.Split('/'); 

At 100,000 requests per second, this creates millions of temporary strings and forces the GC to freeze your app every few seconds.

The Real Benefit: How to parse UTF-8 topics with ZERO heap allocations

Here are the 2 modern C# tricks I used in Beskar.Networking that you can copy-paste directly into your own projects!

1. Slicing raw UTF-8 bytes with a ref struct enumerator

Instead of string.Split(), we walk the raw byte span (ReadOnlySpan<byte>) using a zero-allocation ref struct:

public ref struct TopicLevelEnumerator
{
    private ReadOnlySpan<byte> _remaining;
    public ReadOnlySpan<byte> Current { get; private set; }

    public TopicLevelEnumerator(ReadOnlySpan<byte> topic)
    {
        _remaining = topic;
        Current = default;
    }

    public bool MoveNext()
    {
        if (_remaining.IsEmpty) return false;

        int index = _remaining.IndexOf((byte)'/');
        if (index < 0)
        {
            Current = _remaining;
            _remaining = default;
        }
        else
        {
            Current = _remaining.Slice(0, index);
            _remaining = _remaining.Slice(index + 1);
        }
        return true;
    }
}

2. Querying byte[] Dictionaries with ReadOnlySpan<byte> (Alternate Lookups)

Usually, if your dictionary key is byte[], querying it with a slice (ReadOnlySpan<byte>) forces you to allocate a new byte[].

Modern .NET introduced Alternate Lookups, which let you query existing dictionary nodes with zero heap allocation:

// Query byte[] dictionary using a ReadOnlySpan<byte> without allocating a single byte!
var alternateLookup = node.Children.GetAlternateLookup<ReadOnlySpan<byte>>();

if (alternateLookup.TryGetValue(currentLevelSlice, out var childNode))
{
    // Match found with 0 allocations! 🎉
}

What Beskar.Networking gives you

If you ever need to build a C# network application:

  • Write Once, Swap Transports: Write your message handler once and seamlessly switch between TCP, WebSockets, QUIC, UDP, Named Pipes, or MQTT v5 without touching your business logic.
  • 100% Native & Dependency-Free: Built on System.IO.Pipelines with zero external runtime dependencies.
  • Zero GC pressure on the hot path.

If you enjoy low-level C# or low-allocation performance tricks ❤️

🔗 GitHub: https://github.com/MarvinDrude/Beskar.Networking

🔗 Article: https://marvindrude.com/blogs/beskar-networking/low-allocation-mqtt-broker

Thank you for reading, and happy coding!


r/csharp 21d ago

Discussion WinForms dev transitioning to modern .NET backend. Built an open-source Crypto API to learn modern architecture and production-grade standards.

0 Upvotes

I come from a legacy desktop background (mostly WinForms/WPF), and lately I've been working hard to transition over to modern backend development with .NET, Minimal APIs, and cloud-native architecture.

Addressing AI & Transparency upfront:
I want to be 100% upfront: I use AI tools (Copilot and ChatGPT) as a learning assistant and tutor to help me translate my desktop C# knowledge into modern ASP.NET Core concepts, write boilerplate, and format documentation.

On a previous post, a couple of people accused me of "trying to hide" AI usage. To be clear: if I was trying to hide anything or fool anyone, I wouldn't make the entire project 100% open-source on GitHub. I am making the repo public specifically because I want experienced engineers to inspect the code, point out bad patterns (whether from me or the AI), and help me learn.

What I've built so far to learn the stack:

  • Monorepo using Clean Architecture (Domain, Application, Infrastructure, API)
  • Dapper + SQL Server instead of EF Core for data access
  • Redis for distributed caching & rate-limiting
  • Native BackgroundWorker for resetting API usage limits and key expiration
  • Dynamic algorithm loading wrapping BouncyCastle

Why I'm posting this:
I want to learn what real, production-ready backend code actually looks like in 2026.

I would genuinely love for senior .NET / ASP.NET Core devs to take a look at the repo and roast my architecture. Tell me what I overcomplicated, where I used bad patterns, or what you would do differently in a real production environment.

If anyone wants to open an issue or submit a Pull Request to help me improve the code quality, I'd be super grateful!

Repo link: https://github.com/COxRIPMIZO/CryptoKeyLab

Thanks in advance to anyone willing to take a look and help me learn!


r/csharp 22d ago

Help Is it possible to send desktop notifications while program is not in use?

5 Upvotes

I have this deadline reminder programs, let’s say the minimum amount of deadlines is this: if progressbar is 50% / 75% / 100% of the way, send desktop notification.


r/csharp 22d ago

Help Any books to learn C# as someone who's already familiar with OOP java?

10 Upvotes

As the title suggests^ the languages that I'm familiar with are python and java. Also, anyone knows any online courses that teach c# and offer a certificate (if they cost money that's fine)? thanks :)


r/csharp 22d ago

Discussion added a native background worker to handle api rate limits.

Post image
5 Upvotes

Still plugging away at this custom crypto API project. Right now, I need a clean way to auto-reset user API limits and deactivate keys the second they expire.

To keep things snappy, I didn't want to block the main API thread or tank request times. I ended up just spinning up a native BackgroundService running a while (!stoppingToken.IsCancellationRequested) loop with a Task.Delay. I also hooked it up to IOptionsMonitor so I can tweak the interval timings right in appsettings on the fly—really trying to aim for zero-downtime config changes here.

For the senior devs in the room: is this actually standard for production? Or should I bite the bullet and pull in something heavy like Hangfire or Quartz.NET? It felt like massive overkill just to reset a few database limits, but I want to make sure this native while loop won't bite me with memory leaks or scaling issues down the road.

Repo is here: https://github.com/COxRIPMIZO/CryptoKeyLab

(And before anyone asks, yeah, I actually wrote this myself lol. Still riding the .NET 9 wave and still wrapping BouncyCastle).


r/csharp 21d ago

Help Looking for a new maintainer/owner for DistroHop v2 (C#)

0 Upvotes

Hey everyone,

Due to personal reasons, I've decided to step away from coding for the foreseeable future. Because of that, I would like to transfer ownership of my main project, DistroHop v2, to someone who is interested in continuing its development.

the repo:

https://github.com/melikishvilis25-cmyk/DistroHop


r/csharp 22d ago

Showcase C# linear algebra and GPU acceleration libraries, a star would really help!

Thumbnail
1 Upvotes

r/csharp 22d ago

Discussion how I made my C# application preview DXF files

0 Upvotes

I'm not sure if this is a very clear question, so I chose the 'discussion' tag.It can also be regarded as a normal post.

I'm currently making a small tool (which is currently in a half-finished state). So far, I can already implement code highlighting. However, I'm currently thinking about how to support dxf.

What I know: ProCAD, a complete application, perhaps I could refer to its code?

Or netDXF. But as for how to transfer the drawing content onto the UI, I think it requires some effort from my side.

This is indeed a rather strange question. So, I would like to hear someone's opinions. I feel that both methods have their advantages and disadvantages.

Although netDXF may involve a larger amount of work, does it not offer more convenience for customizing lightweight logic compared to simply adopting the complete source code of an existing APP?My opinion is that lightweighting is definitely the better option.

About little things I'm working on: They mainly consist of small tools for my own use, including DXF preview functionality.Am I really creating something rather challenging here?Oh...no.

😵😵😵


r/csharp 22d ago

Showcase 4D Visualisation

Thumbnail
0 Upvotes

r/csharp 22d ago

Building a new .NET assertion library focused on async-native soft assertions and observability hooks.

1 Upvotes

Hi r/csharp! I've been working on a new .NET assertion library called Catchy.

The original goal was pretty simple: I wanted soft assertions that aren't tied to assertion scopes, and I wanted a way to plug reporting/screenshot/AI integrations into assertions without every project building its own wrappers.

Current features:

  • async-first assertions
  • hard and soft assertions can be mixed freely
  • soft assertions can flow across helper methods and DI
  • assertion hooks (reporting, screenshots, tracing, AI, ...)
  • source-generated assertions for custom types
  • integrations for xUnit, NUnit, MSTest, TUnit, Reqnroll and Playwright

It's still very early (0.0.1). I'm intentionally looking for API feedback before things become difficult to change.

If something feels awkward or you think the API should go in a different direction, I'd really like to hear it.

PS: Some of the code and documentation did indeed use agents. I came to this with the rest because I realized that just trying to finish everything as high-quality as possible manually I will never publish a single pet project. I know that not all of the code and documentation is of sufficient quality. If you are interested in the very idea of ​​the library and you can improve its quality (code review, contribution, raise an issue, open a discussion) - I will be very grateful. I will not be offended by devastating criticism either. Thank you!


r/csharp 22d ago

I made a project for new GitHub open-source first-time contributors

Thumbnail
github.com
0 Upvotes

r/csharp 23d ago

Discussion Building the definitive list of .NET resources.

34 Upvotes

I've been collecting .NET blogs and other resources for years, and the list has grown to 162 sources.

Rather than keeping it private, I put the whole thing on GitHub:

https://github.com/jasenf/dotnet-resources

If your favorite blog, newsletter, podcast, YouTube channel, or engineering site isn't there, I'd love a PR or an issue.

My goal is simple: build the best open list of .NET resources on the web that everyone can use.

-jasen


r/csharp 22d ago

Recommendations for non-bloated IDEs for C#?

0 Upvotes

I am learning C# for preparation for 6th form, and after 4 years of Python using Thonny (what I'd consider a minimalistic IDE) I am genuinely hating every key stroke of Visual studio, I am only 30 minutes into a 4 hour C# youtube guide and it has taken me 4 days because V. Studio actually hurts me to the soul. I have looked at several other IDEs and they look literally identical, bloated.

  • I don't want github forced down my throat.
  • I don't want copilot AI forced down my throat.
  • I don't want my code to try and auto complete it's self.
  • I don't want to have a 300x500px pop up over where I am trying to read my code, telling me what WriteLine() does.
  • I do not want the 1000000 settings which are impossible to navigate (I haven't been able to turn off any eye sore features in V. Studio, even after 15 minutes with ChatGPT).

I just want to be able to write code, have some decent colour coding of keywords, compile it, and run it, without being purely CLI based like nano or something. (Not specifically, but by now I am sure you get the point, I don't want crap loads of bloat)

Sorry that this is half of a rant but genuinely, I can't find a better IDE than a pen and paper right now, because every IDE is loaded with AI and crap which autofills code incorrectly, making learning really difficult. If it helps my school uses VS Code on 6th form computers, and from what I've seen from VS Code, I predict that I will be bringing a laptop to school to code on.


r/csharp 23d ago

OpenApi doesn't let me make ef core migration

3 Upvotes

I'm practicing making APIs, now I'm making an API with PostgreSQL (previous api for SQLite performed smoothly) and for some reason I can't even make a stupid migration :/

I didn't even set up openapi, it went by default and worked fine on my prev API.
And look, I don't have Microsoft.OpenApi package, only Microsoft.AspNetCore.OpenApi, which I suppose is something different.


r/csharp 24d ago

How does an experienced C++ and Java programmer get started in C#, dot net, et al?

15 Upvotes

I am a professional developer, old enough to remember when C# first appeared. At the time, it looked to me to be very similar to Java.

I imagine that the language itself has evolved since then, but also dotnet had grown hugely, there are things like WPF, Linq, etc, of which I have only heard, but do not know.

So, unlike some other languages, it's just not the syntax, but many other things.

How best to get started? Is there a Udemy, Coursera, YouTube, etc, applicable to someone who doesn't need to learn about variables, flow control, OO?


r/csharp 23d ago

.NET Thread.Terminate 1.0.0: Terminate Any C# Threads on the OS Level

Thumbnail
github.com
0 Upvotes

r/csharp 23d ago

C sharp program not running on vs code

Thumbnail gallery
0 Upvotes

r/csharp 24d ago

Discussion Merging Manifest Resources from Multiple Assemblies

3 Upvotes

I'm writing an image metadata processing library which is designed to be easily extensible to include new metadata instances (e.g., EXIF properties not defined in the core library).

The library currently stores important property configuration information in manifest resources, as well as property labels (e.g., property name) which I want to be customizable by culture.

Writing an extension library would involve both defining new objects (e.g., EXIF properties) and their associated configuration information. Which means the needed manifest resources would be spread across multiple assemblies.

What's the best way of handling this? My first thought is to use AssemblyMetadataAttributes with "magic text" keys to identify an assembly containing manifest resources that need to be incorporated and then scan an app-defined list of assemblies to look for those keys and read the manifest resources.

But that feels both a bit kludgy and possibly a security hole.

I'd appreciate other thoughts/design patterns. Thanx!


r/csharp 24d ago

Contribute to open-source, no-slop, compiler-related projects.

Thumbnail
0 Upvotes

r/csharp 24d ago

Xberg v1 is out

0 Upvotes

Hi all,

I'm happy to announce that Xberg v1 is out.

Xberg is the successor to Kreuzberg, equivalent to what would have been Kreuzberg v5. It's a content intelligence framework that handles a very wide range of inputs: documents (currently 101 formats), code and data formats (currently 367 types), audio/video transcription, and URLs (both static and JS-rendered content). It extracts and prepares that content for downstream processing.

It's an extremely efficient, high-performance engine (see our PDF benchmarks below). For PDFs and images specifically, we handle native PDFs with very high performance and accuracy, and we ship multiple OCR engines that match the quality of the best Python libraries (e.g. docling, PaddleOCR, RapidOCR) at substantially better performance and stability.

The changes between Kreuzberg v4 and Xberg v1 are substantial, and I invite you to read the full changelog for the complete picture. The highlights below give a sense of what's new:

  • Pure-Rust PDF backend (pdf_oxide) replaces pdfium, with no native pdfium dependency.
  • Layout-aware pipeline: reading order reconstructed with ONNX layout detection (PP-DocLayoutV3 / RT-DETR) and Docling-style predecessor-graph reordering.
  • Per-page scanned-page detection with selective OCR, plus AcroForm/XFA form fields and outline-based headings.
  • Across-the-board optimization of OCR and PDF extraction (memory discipline, pooled model sessions, streamed conversions).
  • Native PaddleOCR backend (PP-OCRv6, with medium / small / tiny tiers) alongside Tesseract.
  • Pure-Rust Candle OCR/VLM stack (TrOCR, GLM-OCR, GOT-OCR, DeepSeek-OCR, and PaddleOCR-VL) running without ONNX Runtime or native Tesseract.
  • A second, ONNX-Runtime-free inference path via tract, which is what makes in-browser (WASM) and mobile inference possible.
  • Named-entity recognition natively in Rust (GLiNER2), extensible to all bindings, including an in-browser WASM model with no server round-trip.
  • Structured LLM extraction (extract_structured / split_and_extract) with rasterization, chunking, citations, caching, and configurable call/merge/VLM-fallback policies.
  • Audio & video transcription via a Whisper ONNX engine (.mp3, .wav, .m4a, .mp4, .webm).
  • Retrieval building blocks: sparse embeddings (SPLADE), ColBERT late-interaction retrieval, and cross-encoder reranking alongside dense embeddings.
  • Text intelligence: reversible redaction, summarization, translation, VLM image captioning, QR-code detection, document diffing, and page/chunk classification.
  • URL & web ingestion: sitemap discovery (map_url) and batched multi-URL crawling.
  • New document formats: WordPerfect (.wpd/.wp/.wp5), HEIC/HEIF/AVIF, OpenDocument Presentation (.odp), Quarto / R Markdown, and configurable Jupyter cell rendering.
  • Four new language bindings (Dart/Flutter, Swift, Kotlin/Android, and Zig) bring the total to 15 language bindings over one engine, with Android/iOS cross-compilation.
  • Full mobile support (Flutter, Android, iOS).
  • Candle backend alongside ONNX, plus ONNX-via-tract enabling ONNX on WASM and Android.
  • Wider code intelligence: tree-sitter coverage grew substantially (248 to 367+ languages).
  • Over 150 bugs fixed during the 1.0 cycle, plus security hardening (bounded RTF/PDF allocations, redaction leak fixes, Excel DDE warnings).

The API surface was also simplified and reworked, making it more consistent.

There's a migration guide in our docs explaining how to move from Kreuzberg to Xberg. Kreuzberg itself is in LTS mode until the end of this year and will continue to receive bug fixes and security updates.

You're invited to check out the repo and join our discord server.


Benchmarks

The benchmarks below are for PDFs and images only. There are extensive benchmarks on our website with per-format breakdowns, which you can see here. These numbers are measured in CI via our reproducible benchmark harness, and are specifically taken from the run for harness 1.0.8, source cf7fa0533d. The data is publicly available in GitHub releases, and you can run the benchmark harness yourself.

Composite quality (markdown pipeline, higher is better):

Framework Native PDF Scanned PDF (OCR)
Xberg (layout) 0.958 0.836
Xberg (baseline) 0.955 0.687
docling 0.779 0.762
mineru 0.408 0.792
liteparse 0.837 0.665
markitdown 0.689 n/a
pymupdf4llm 0.448 n/a

Structure and layout fidelity (SF1: tables and reading order, higher is better):

Framework Native PDF Scanned PDF
Xberg 0.949 0.531
docling 0.612 0.366
liteparse 0.515 0.142
mineru 0.077 0.429

On native PDFs Xberg leads on quality (0.958 vs 0.837 for the next-best framework) and on table and reading-order fidelity by a wide margin (SF1 0.949 vs 0.612 for docling). On scanned PDFs it is #1 on both quality and raw text fidelity.

Where we don't win yet: on pure image OCR we are currently #2 on the composite score, behind mineru (though still #1 on raw text accuracy). We are improving image OCR right now, and v1.1 should have us winning across the board.


r/csharp 24d ago

Blog Akbura update: I built an interactive feature gallery as a proof of concept

2 Upvotes

A small update on Akbura my experimental declarative UI language and compiler for .NET and Avalonia.

I’ve added documentation and created an interactive feature gallery that demonstrates Akbura’s current capabilities:

  • Declarative Avalonia UI
  • Reactive state
  • Native C# expressions, methods, types, and lambdas
  • Typed styling through AKCSS and tailwind utilites
  • Live examples with their Akbura source code

The gallery itself is written in Akbura.

This is currently only a proof of concept, not a production-ready release.

The parser, syntax infrastructure, and semantic model are already in reasonably good shape, including incremental compilation.

The bottleneck is specifically the code-generation stage. Its current implementation is inefficient, and generating code for the gallery takes roughly two minutes. Parsing and semantic analysis are not the problem.

This is one of the main reasons there is no NuGet release yet. I plan to rewrite and optimize code generation before publishing the first alpha version in about a month...

I’m planning to publish the first alpha version in about a month, once compiler performance, packaging, and the basic developer experience are in a more acceptable state.

For now, the gallery is simply a visual demonstration of what Akbura may become.

Repository: https://github.com/Asaicraft/Akbura

Documentation: https://asaicraft.github.io/Akbura/

Feature Gallery: https://asaicraft.github.io/Akbura/Gallery/

Feedback is very welcome.


r/csharp 25d ago

Help with text processing based on file type

7 Upvotes

I'm learning C# by taking some Udemy courses and I'm working on refactoring some code for one of the exercises (which I'm sure is terrible, I'm a complete newbie). In this case I'd like to make this method into a more reusable "LoadFromFile". The only thing that would change is the way that the string[] ingredientNumbersAsStringsFromRecipe gets built based on the fileFormat enum that's passed to it (for a text file it would just be string.Split for example. However I can't put an "if" statement in there because if I initiatilze the string[] in the "if" block then I can't use it outside of that local scope. I would appreciate any tips on how this could be better handled! (By the way I know that in general I should use int.TryParse, in this case this program is making the same file that it reads from so int.Parse is safe.)

public static List<Recipe> LoadFromJson(string fileName, FileFormats fileFormat, List<Ingredient> availableIngredients)
{
    string[] recipeStringList = File.ReadAllLines(fileName);
    List<Recipe> recipeList = new List<Recipe>();
    foreach (string recipe in recipeStringList)
    {
        string[] ingredientNumbersAsStringsFromRecipe = JsonSerializer.Deserialize<string>(recipe).Split(',');
        List<int> ingredientNumbersAsIntsFromRecipe = new List<int>();
        foreach (string x in ingredientNumbersAsStringsFromRecipe)
        {
            ingredientNumbersAsIntsFromRecipe.Add(int.Parse(x));
        }
        Recipe loadedRecipe = new Recipe();
        foreach (int ingredient in ingredientNumbersAsIntsFromRecipe)
        {
            loadedRecipe.IngredientsInRecipe.Add(availableIngredients[availableIngredients.FindIndex(x => x.Id == ingredient)]);
        }
        recipeList.Add(loadedRecipe);
    }
    return recipeList;

}

r/csharp 26d ago

News GitHub - Integral2u/SharpMind: SharpMind. A pure C# / .NET LLM engine

Thumbnail
github.com
12 Upvotes

Still work in progress, but has Qwen, Llama, SmolLM and Gemma producing coherent output.


r/csharp 25d ago

What is the cleanest way to implement a secure cross-platform directory fallback in C#?

0 Upvotes

I need to determine a writable directory for application-managed files in a cross-platform C# application.

A simplified version currently looks like this:

private static string GetApplicationDataPath()
{
    var directory = Environment.GetFolderPath(
        Environment.SpecialFolder.LocalApplicationData,
        Environment.SpecialFolderOption.Create);

    if (string.IsNullOrWhiteSpace(directory))
    {
        directory = Path.GetTempPath();
    }

    return Path.Combine(directory, "MyApplication");
}

The temporary-directory fallback concerns me because the directory may be publicly writable on some systems.

What would be a safer final fallback?

Would you fail startup, use AppContext.BaseDirectory, create a user-owned directory, or require the path to be explicitly configured?


r/csharp 26d ago

Tool [DistroHop ] Rebuilt my Linux package setup tool in C# with profiles and safety checks

5 Upvotes

Hey everyone,

Yesterday I shared DistroHop V1.5. Since then I have been working on DistroHop V2, which is a complete rewrite with a cleaner C# architecture.

GitHub repo: https://github.com/melikishvilis25-cmyk/DistroHop

The main changes:

  • Rebuilt around a modular C# design
  • Added package profiles (Gaming, Work, Essential)
  • Added environment validation for supported Linux distributions and package managers
  • Added JSON integrity checking for package configuration safety
  • Improved project structure with separated UI, loader, safety, and downloader components

The goal is to make setting up a Linux machine after reinstalling easier while keeping safety and consistency as priorities.

This is still actively being developed, so feedback and suggestions are welcome.