Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

How to Begin Using OpenCV in .NET?

Leave a Comment

One well-known open-source framework for image processing, computer vision, and machine learning is called OpenCV (Open Source Computer Vision Library). Although OpenCV has its origins in C++, OpenCvSharp, a.NET wrapper for the OpenCV library, offers bindings that enable it to be used with ease in.NET applications.

This article is a beginner-friendly guide to getting OpenCV up and running in your .NET environment, demonstrating a basic example: loading an image and converting it to grayscale.

Prerequisites

Before diving into code, ensure you have the following set up.

  1. Visual Studio (or any C# IDE of your choice).
  2. .NET 5, .NET 6, or higher installed on your system.
  3. Basic familiarity with C# and .NET projects.
1. Set Up OpenCvSharp in Your .NET Project

To use OpenCV in .NET, we'll install the OpenCvSharp NuGet package. This provides high-level bindings to OpenCV's functionality within a .NET application.

Steps to Install OpenCvSharp
  1. Create a New .NET Project: Create a new console application named OpenCVExample.
  2. Install the OpenCvSharp NuGet Packages: Run the following in your terminal or Package Manager Console in Visual Studio.
    dotnet add package OpenCvSharp4
    dotnet add package OpenCvSharp4.runtime.win  # For runtime support on Windows
2. Load an Image and Convert It to Grayscale

Now that OpenCvSharp is installed, let’s write a simple program that.

  1. Loads an image.
  2. Converts the image to grayscale.
  3. Displays the original and grayscale images.

Here’s the complete example.

Program Code

using System;
using OpenCvSharp;

class Program
{
    static void Main(string[] args)
    {
        // Path to the image file (change this to the path of your image file)
        string imagePath = "sample.jpg";
        // Step 1: Load the image
        Mat inputImage = Cv2.ImRead(imagePath, ImreadModes.Color);
        if (inputImage.Empty())
        {
            Console.WriteLine("Failed to load the image. Check the file path.");
            return;
        }
        Console.WriteLine("Image loaded successfully!");
        // Step 2: Convert the image to grayscale
        Mat grayImage = new Mat();  // Create a new matrix to store the grayscale image
        Cv2.CvtColor(inputImage, grayImage, ColorConversionCodes.BGR2GRAY);
        Console.WriteLine("Image converted to grayscale.");
        // Step 3: Display both images (original and grayscale)
        Cv2.ImShow("Original Image", inputImage);
        Cv2.ImShow("Grayscale Image", grayImage);
        // Wait for a key press before closing the image display windows
        Console.WriteLine("Press any key to close the image windows.");
        Cv2.WaitKey();
        Cv2.DestroyAllWindows();
    }
}
3. Run the Application

Steps

  1. Add the Image File: Place the image (sample.jpg) in the bin\Debug\net8.0 project folder, or specify the absolute path to your image file.
  2. Build and Run the Code: Press Ctrl + F5 in Visual Studio or run from the terminal.
  3. Result
    • Two separate windows will open.
      • One shows the original image.
      • One shows the grayscale version.
    • The console will display messages about the image processing status.
4. Key Methods and Concepts

Let’s break down some essential parts of the code.

(i) CV2.ImRead(): Load an Image
  • Loads the image from the path specified.
  • The second parameter specifies the color mode.
    • ImreadModes.Color (default): Loads in color (BGR format).
    • ImreadModes.Grayscale: Directly loads the image as grayscale.
(ii) Cv2.CvtColor(): Color Conversion
  • Converts an image from one format to another.
  • In our example, we convert the original image (in BGR format) to grayscale.
    Cv2.CvtColor(inputImage, grayImage, ColorConversionCodes.BGR2GRAY);
(iii) CV2.ImShow(): Display an Image
  • Creates a window and displays the image.
  • Parameters
    • Window Name: Unique name for the display window.
    • Image: The Mat object (photo) to display.
(iv) CV2.WaitKey() and Cv2.DestroyAllWindows()
  • Cv2.WaitKey() pauses the execution and keeps the image windows open until a key is pressed.
  • Cv2.DestroyAllWindows() closes all image display windows once you're done.
5. Next Steps

Now that you've successfully loaded and processed your first image with OpenCV in .NET, the possibilities are endless! Here are some recommended next steps.

Step 1. Try with Other Image Processing Functions.

Explore methods such as blurring, edge detection, and thresholding. Examples include,

  • Cv2.GaussianBlur(): Apply a Gaussian blur to an image.
  • Cv2.Canny(): Perform edge detection.

Example of detecting edges in a grayscale image.

Mat edges = new Mat();
// Edge detection with thresholds
Cv2.Canny(grayImage, edges, 100, 200);
Cv2.ImShow("Edge Detection", edges);

Step 2. Handle Videos.

Use VideoCapture from OpenCV to process video files or webcam streams.

Step 3. Explore Image Manipulations.

  • Cropping
  • Rotating
  • Resizing images

Step 4. Utilize Object Detection Filters.

Explore advanced topics such as object detection, face recognition, or feature extraction.

Conclusion

Congratulations! You’ve taken your first steps in using OpenCV with .NET through OpenCvSharp. Loading an image and converting it to grayscale is a foundational exercise, setting the stage for more advanced operations, such as image enhancements, object detection, or deep learning integrations.

By adding OpenCV to your software development toolkit, you unlock a world of possibilities for building applications in image processing, computer vision, and beyond. So, keep experimenting and take your application development to the next level!

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 10.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

Read More

SQL Server Integration in Aspire Applications: .NET Aspire Integrations

Leave a Comment

Databases, caches, message brokers, APIs, telemetry systems, and other supporting technologies are all essential to modern cloud-native applications. Writing business logic is only one aspect of creating such an application; another is carefully connecting these services in a scalable, observable, and maintainable manner. By providing a strong application model that makes it simple for developers to create, set up, and maintain service dependencies,.NET Aspire reduces this complexity.

What do Aspire Integrations bring to the Table?

When you add an integration to an Aspire project, you get.

  • Typed configuration and DI setup: Auto-wiring of client libraries with configuration via strongly typed options.
  • Health checks: Automatic inclusion of health checks for critical dependencies.
  • Connection string propagation: Seamless sharing of connection strings across projects using Aspire's service discovery.
  • Dashboard visibility: Integrated resources are visible and traceable through the Aspire Dashboard.
  • Simplified Dev Experience: You don’t have to manually set up service bindings or write boilerplate configuration.

These integrations promote a cloud-native design, while also making local development and testing smoother and more predictable.

Common Integrations in .NET Aspire

.NET Aspire comes with official and community-supported packages that make integrating third-party services a breeze. Below is a curated list of popular tools and services across different categories that work seamlessly with Aspire.

Databases
Service Integration Package Notes
SQL Server Aspire.Hosting.SqlServer Connection string, health check, and discovery are handled automatically.
PostgreSQL Microsoft.Extensions.Hosting.PostgreSql Community-supported; connection string injection.
MySQL Microsoft.Extensions.Hosting.MySql Similar benefits to PostgreSQL.

Caching & Data Store
Service Integration Package Notes
Redis Microsoft.Extensions.Caching.StackExchangeRedis.Aspire Adds Redis as a resource, injects connection string, auto configures.
MongoDB MongoDB.Driver.Aspire (community) Mongo client setup via Aspire DI.

Messaging & Eventing
Service Integration Package Notes
RabbitMQ Tye.Hosting.RabbitMQ.Aspire (community) Easy messaging setup.
Azure Service Bus Microsoft.Azure.ServiceBus.Aspire (planned) Advanced integration expected in future releases.

Observability & Monitoring
Tool Integration Package Notes
OpenTelemetry Microsoft.Extensions.Telemetry.Aspire Auto-wires tracing/metrics.
Grafana + Prometheus Community Templates Can export Aspire metrics here.

External Services & APIs
Type Example Aspire Support Notes
HTTP APIs REST, GraphQL, gRPC APIs Use .WithEndpoint() to define upstream APIs.
Cloud SDKs Azure, AWS Aspire config + DI bindings are supported manually.

.NET Aspire SQL Server integration

Let’s see in action how to get an Aspire Integrations with SQL Server.

When building distributed applications, a database is often a critical component.

.NET Aspire simplifies integrating SQL Server into your project by providing first-class support through its Aspire.Hosting.SqlServer package.

This integration focuses on,

  • Spinning up SQL Server instances (locally or containerized) during development.
  • Managing connection strings automatically.
  • Sharing database endpoints across your application components.
  • Adding health checks for SQL Server availability.
  • Visualizing the SQL Server resource in the Aspire Dashboard.
Setting Up SQL Server Integration

Step 1. Install the SQL Server Aspire Package.

In your AppHost project, run.

dotnet add package Aspire.Hosting.SqlServer

Or simply visit to manage NuGet Packages and “Aspire.Hosting.SQLServer” in App Host.


This package brings in the AddSqlServer extension method that makes adding SQL easy.

Step 2.
Define the SQL Server Resource.
In your Program.cs inside the AppHost project.

SQL Server Resource

Here is what this code does.

  1. Define a parameter for the SQL Server password.
    IResourceBuilder<ParameterResource>? dbPassword =
        builder.AddParameter("dbPassword", true);

Key Points in This Setup

  • AddParameter("dbPassword", true): Securely prompts for the database password if it's not already configured.
  • AddSqlServer("sql", dbPassword, 1455): Adds a SQL Server resource running on custom port 1455 and uses the provided password.
  • .WithLifetime(ContainerLifetime.Persistent): Ensures the SQL Server container persists between runs.
  • AddDatabase("database"): Defines a database inside SQL Server for use by the application.
  • .WithReference(db) and .WithReference(MyAPI): Links services together by passing resources like connection strings automatically.

Step 3. Configure Parameters Securely.

Instead of hardcoding sensitive information like database passwords in your code, Aspire encourages you to use Parameters.

In your appsettings.json, define the SQL Server password under the Parameters section.

  • dbPassword is injected at runtime into the SQL Server resource.
  • You can also override it using environment variables or secret managers for production.
  • This keeps your applications secure, configurable, and environment-agnostic.

Important. If the “dbPassword” is not found in your settings or environment, Aspire will prompt you to enter it at startup (because of the true flag in AddParameter("dbPassword", true)).

Pro Tip. Managing Sensitive Parameters in .NET Aspire Applications.

  • Never hardcode secrets like passwords directly in code files.
  • Prefer appsettings.json for local development, but move to secret managers like Azure Key Vault or environment variables in production.
  • Use AddParameter with isSecret: true to ensure Aspire handles the value securely, and prompts when missing.
  • Do not commit real secrets into your source control repositories (e.g., GitHub).
  • Leverage dotnet user-secrets for development.
    dotnet user-secrets set "Parameters:dbPassword" "YourSecurePassword"
  • Configure deployment environments to provide required parameters securely during CI/CD pipeline runs.
Aspire Dashboard View

When you run the application, the Aspire Dashboard will show your SQL Server alongside your services, making the architecture and dependencies crystal clear.

Example

[SQL Server] <--- connected to ---> [Web API]
Aspire Dashboard View

When you run the application, the Aspire Dashboard will show your SQL Server alongside your services, making the architecture and dependencies crystal clear.

Example

[SQL Server] <--- connected to ---> [Web API]
SQL

Step 1. SQL Server and Database Creation Verification.

  • Open your application in the Aspire Dashboard (localhost:17010).
  • In the Resources tab, you will see a list of services.
  • Notice two services.
    • SQL (SQL Server): Running state with the source pointing to mcr.microsoft.com/mssql/server2022-latest.
    • Database: Running state.

  • These were automatically created based on the definitions provided in your Program.cs file.
  • The SQL Server service is configured to expose on tcp://localhost:1455, as per the given port number.

Step 2. Verifying API Environment Variables

  • In the Aspire Dashboard, under Resources, locate the API service.
  • Click the three dots (...) next to the API service.
  • Select View details from the dropdown menu.

Step 3. Checking the Database Connection String.

  • In the Project: API details view, scroll to the Environment Variables section.
  • Look for the environment variable named: ConnectionStrings__database.
  • You will find the database connection string, such as Server=127.0.0.1,1455;User ID=sa;Password=Nit1n5QL;
  • This confirms that the API service has the database connection string injected correctly through environment variables.

Step 4. Aspire Action Reflected in Docker (Local).

You can see the side effects of Aspire's local work in Docker Desktop.

  • Images: An image mcr.microsoft.com/mssql/server:2022-latest is pulled into Docker.
  • Containers: A container sql-xxx is running, exposing the SQL Server on port 1455.

Result: Aspire used Docker to spin up the local SQL server dynamically for your app.

Area Action by Aspire Result Seen Where
Database Server SQL Server container created on port 1455 Docker Desktop (Containers tab)
Database Resource Database initialization or setup done Aspire Dashboard - Resources
API Env Setup Database connection string injected automatically Aspire Dashboard - API - Environment Variables
Docker Image MSSQL Image pulled if not present Docker Desktop (Images tab)

Debugging the Connection String: Verify reading the environment variables

Let’s try reading the Connection string from the environment variables, As we have added the reference of SQL Server database to the Weather API Project from App host with Aspire Hosting.

To do that I have added a code to read the connection string from application configuration variables with the name “database” in my API Controller’s Get method “GetWeatherForecast”:

Run the solution and open API swagger to hit the API End Point for debugging the code with a breakpoint on the same line.

You can see the connection string is available for the API Project from the application configurations even though we don’t have any local parameter the name of “database”.

Here is the connection string we got.

Server=127.0.0.1,1455;User ID=sa;Password=Nit1n5QL;TrustServerCertificate=true;Initial Catalog=database

Testing in SSMS

If you want you can use the same connection string in the SQL Server Management Studio to check this Database and its table, which may help you inthe future.

Paste the same connection String in the last tab “Additional Connection Parameters” and hit connect.

I am sure you must be able to see the connected Server and Database in SSMS’s Object Explorer.

Why Use SQL Server Integration with Aspire?
Benefit Description
Fast Setup No manual container configuration is needed.
Secure Connection Management Credentials and connection strings are injected safely.
Automatic Health Monitoring Built-in health checks for SQL Server connectivity.
Easy Switching Easily swap local dev SQL Server with Azure SQL for production.

Similarly, you can use Aspire Immigrations for Databases and other tools.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

A Brief Introduction to SignalR in.Net Core

Leave a Comment

These days, people expect apps to updates in real-time like live chats, notifications, or game scores, without refreshing the page again and again. SignalR in .NET Core helps you do just that by making real-time communication easy. In this blog, we’ll quickly show you how to get started with it in your own .NET Core project.

SignalR: What is it?

Microsoft created the SignalR real-time messaging library, which enables two-way communication between clients—such as desktop programs, mobile apps, or web browsers—and the server. Adding real-time functionality to your web apps is simple and scalable, allowing users to get updates and notifications quickly without requiring manual requests or page refreshes.

Usages of SignalR

Here are some common use cases where SignalR can be a great fit for adding real-time functionality to your applications.

  • Chat Applications: SignalR is perfect for building mid-level chat applications where users can exchange messages instantly. It supports sending messages to all users, specific groups, or individual users in real-time. For a higher-level chatting application, XMPP or WebSocket is the best option.
  • Notifications: You can use SignalR to push real-time notifications to users for events such as new messages, system alerts, or order updates without making them refresh the page.
  • Live Dashboards: For use cases like monitoring systems or admin panels, SignalR enables real-time dashboards that automatically refresh as data changes, helping users make quick decisions.
  • Online Exams or Quizzes: SignalR can be used in online test platforms to push time updates or instant results to participants during live sessions.
  • Live Polls and Q&A: Apps that conduct live polls or Q&A during webinars or events can benefit from SignalR by showing real-time responses and updates to all viewers instantly.
  • Collaboration Tools: SignalR is again helpful in mid-level collaborative apps where multiple users need to work together in real-time—like document editing, whiteboards, or project tracking tools.
How to use in an ASP.NET Core project?

To use in a .NET Core project, you have to install the SignalR NuGet package. Run the below command from NuGet Package Manager or PowerShell

# .NET CLI
dotnet add package Microsoft.AspNet.SignalR

# Nuget Package Manager
NuGet\Install-Package Microsoft.AspNet.SignalR
Bash

Now you have to create a Hub. Let's say we are building a chatbot using SignalR; hence, we are creating a chat hub. This hub will handle the server-side logic for sending messages.

// ChatHub.cs
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

Next, we have to register ChatHub in the program.cs file so that it can initialize at the time of starting.

// program.cs

var builder = WebApplication.CreateBuilder(args);

// Register services
builder.Services.AddRazorPages();
builder.Services.AddSignalR(); // Register SignalR

var app = builder.Build();

// Configure middleware
app.UseStaticFiles();
app.UseRouting();

// Map endpoints
app.MapRazorPages();
app.MapHub<ChatHub>("/chathub"); // Map Chathub with an endpoint

app.Run();
How to use in Front-end projects?

As our backend code is reday. Now let's use this in the frontend. Either you can use CDN script of SignalR or npm package of SignalR in case of Angular, React, or Next JS like below.

Using CDN

<!-- CDN for SignalR -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.5/signalr.min.js"></script>

<script>
    // Setting up the endpoint
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/chathub")
        .build();

    connection.on("ReceiveMessage", (user, message) => {
        const msg = `${user} - ${message}`;
        const li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("messagesList").appendChild(li);
    });

    connection.start()
        .catch(err => console.error(err.toString()));

    document.getElementById("sendButton").addEventListener("click", () => {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;

        connection.invoke("SendMessage", user, message)
            .catch(err => console.error(err.toString()));
    });
</script>
Using an NPM package in Angular

To use in Angular, you have to install the SignalR npm package

npm install @microsoft/signalr

Then have to create a service for the communication.

/* signalr.service.ts */

import { Injectable } from '@angular/core';
import * as signalR from '@microsoft/signalr';

@Injectable({
  providedIn: 'root'
})
export class SignalrService {
  private hubConnection: signalR.HubConnection;
  public messages: string[] = [];

  public startConnection(): void {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:5000/chathub') // URL to be fetched from environment config
      .build();

    this.hubConnection
      .start()
      .then(() => console.log('Connection started'))
      .catch(err => console.log('Error while starting connection: ' + err));

    this.hubConnection.on('ReceiveMessage', (user: string, message: string) => {
      this.messages.push(`${user}: ${message}`);
    });
  }

  public sendMessage(user: string, message: string): void {
    this.hubConnection.invoke('SendMessage', user, message)
      .catch(err => console.error(err));
  }
}

And now it's time to consume this service from a component.

/* app.component.ts */
/* In the blog app.component has been used. In actual project, please create a new component and register */

import { Component, OnInit } from '@angular/core';
import { SignalrService } from './signalr.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {
  user = '';
  message = '';

  constructor(public signalRService: SignalrService) {}

  ngOnInit(): void {
    this.signalRService.startConnection();
  }

  sendMessage(): void {
    this.signalRService.sendMessage(this.user, this.message);
    this.message = '';
  }
}

In the HTML, place the text box & div to view the messages.

<!-- app.component.html -->

<div>
  <input [(ngModel)]="user" placeholder="Your name" />
  <input [(ngModel)]="message" placeholder="Message" />
  <button (click)="sendMessage()">Send</button>

  <ul>
    <li *ngFor="let msg of signalRService.messages">
      {{ msg }}
    </li>
  </ul>
</div>
Architectural components of SignalR

Now, as you know how to use SignalR, let's also deep dive into the architectural components of SignalR. Here are the main parts that make up the SignalR setup.

  • Hubs: A Hub is a central part of SignalR that manages communication between the server and connected clients. It takes care of handling connections, sending messages, and converting data formats. With Hubs, clients can call server-side methods, and the server can also call methods on the clients.
  • Clients: Clients are applications or devices, such as browsers or mobile apps, that connect to the SignalR server to exchange real-time messages. Using the SignalR client library, these clients can easily send messages to the server and receive updates without delay.
  • Transports: SignalR uses different methods, called transports, to create and maintain the connection between the client and the server. These include WebSockets, Server-Sent Events (SSE), Long Polling, and Forever Frame, depending on what the client and server support.
  • Connections: A connection refers to the link between a single client and the SignalR server. Each connection has a unique ID that keeps track of the client and sends messages to the right one.
  • SignalR Server: The SignalR server handles all the communication between clients. It manages connections, routes messages to the right clients, and controls the flow of data through the pipeline.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

 

Read More

What is Interlocked In .NET?

Leave a Comment

In multithreaded applications, multiple threads can access and modify shared variables concurrently. This can lead to race conditions. The System.Threading.Interlocked class provides atomic operations on variables, ensuring thread safety without using locks.


Common Use Cases

  • Counters (Increment/Decrement)
  • Flags (Boolean states)
  • Exchange operations
  • Compare-and-swap (CAS)

Why Use Interlocked?

  • Atomic operations: Guaranteed to complete without interruption
  • Lightweight: Faster than locking mechanisms
  • Lock-free: Reduces the chance of deadlocks

Thread-Safe Counter Example
using System;
using System.Threading;

class Program
{
    private static int counter = 0;

    static void Main()
    {
        Thread[] threads = new Thread[10];

        for (int i = 0; i < threads.Length; i++)
        {
            threads[i] = new Thread(() =>
            {
                for (int j = 0; j < 1000; j++)
                {
                    Interlocked.Increment(ref counter);
                }
            });
            threads[i].Start();
        }

        foreach (var t in threads) t.Join();

        Console.WriteLine($"Final counter value: {counter}");
    }
}


Methods in Interlocked

  • Interlocked.Increment(ref int location)
  • Interlocked.Decrement(ref int location)
  • Interlocked.Add(ref int location, int value)
  • Interlocked.Exchange(ref T location, T value)
  • Interlocked.CompareExchange(ref T location, T value, T comparand)

Thread-Safe Flag Example (Boolean)
Booleans aren't directly supported by Interlocked, but you can simulate them using integers:
private static int isRunning = 0;

if (Interlocked.CompareExchange(ref isRunning, 1, 0) == 0)
{
    try
    {
        // Do work
    }
    finally
    {
        Interlocked.Exchange(ref isRunning, 0);
    }
}


Summary
Interlocked is ideal for low-level concurrency control. Best for simple shared variable updates. Use it when you want lock-free synchronization. For complex data structures, prefer lock or concurrent collections.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

What's New in C# 14 and ASP.NET Core 10?

Leave a Comment

C# 14 introduces several powerful language features focused on performance, flexibility, and developer convenience.

 

Here are the key updates:

Implicit Span Conversions

C# 14 offers first-class support for the System.Span<T> and System.ReadOnlySpan<T>. These types are designed for high-performance, memory-safe manipulation of contiguous data. C# 14 introduces implicit conversions between.

  • T[ ] → Span<T>
  • T[ ] → ReadOnlySpan<T>
  • Span<T> → ReadOnlySpan<T>

This means you can now write APIs that accept spans and call them with arrays, reducing the need for explicit casts and avoiding unnecessary allocations.

void Print(ReadOnlySpan<char> data)
{
    foreach (var ch in data)
        Console.Write(ch);
    Console.WriteLine();
}

char[] buffer = { 'H', 'e', 'l', 'l', 'o' };
// Implicitly converts char[] to ReadOnlySpan<char>
Print(buffer);

Benefits

  • Zero allocations
  • Type safety
  • Improved performance for memory-intensive operations
Unbound Generic Types in the nameof

Before C# 14, you could only use closed generic types with nameof, such as nameof(List<int>). With C# 14, you can now reference unbound generics in the nameof, enabling cleaner and more flexible metadata or logging scenarios.

Console.WriteLine(nameof(Dictionary<,>));
Console.WriteLine(nameof(List<>));

Output

  • Dictionary
  • List
Simple Lambda Parameters with Modifiers

C# 14 allows you to use modifiers like ref, out, in, scoped, and ref readonly in lambda parameters, even without specifying the type. Previously, you had to provide full-type declarations to use modifiers.

delegate bool TryParse<T>(string text, out T result);
private static void LambdaParameterModifiersExample()
{
  TryParse<int> tryParse = (text, out result) => int.TryParse(text, out result);

  if (tryParse("123", out var num))
  Console.WriteLine($"Parsed: {num}");
  else
  Console.WriteLine("Failed to parse");
}
C#

Benefits

  • Cleaner syntax
  • Better support for modern API design
  • Enhanced lambda expressiveness

.NET 10 Library Enhancements

.NET 10 introduces powerful enhancements to its base-class libraries. Here's a breakdown of the most impactful additions.

Finding Certificates by Thumbprint (SHA-2 & SHA-3)

Before .NET 10: Only SHA-1 hash thumbprints were supported, limiting security standards. Now, you can use secure hashing algorithms like SHA-256 or SHA-3 directly.

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);

string thumbprint = "ABCD1234...";
X509Certificate2Collection certs = store.Certificates.FindByThumbprint(HashAlgorithmName.SHA256, thumbprint);

if (certs.Count == 1)
{
    Console.WriteLine("Certificate found: " + certs[0].Subject);
}

Benefits: Stronger certificate validation in secure systems.

Improved PEM File Parsing (UTF-8)

Initially, manual encoding conversion was needed to read UTF-8 PEM files. Now, Native support for UTF-8 parsing simplifies the process.

byte[] pemData = File.ReadAllBytes("key.pem");
PemFields pemFields = PemEncoding.FindUtf8(pemData);
string label = Encoding.UTF8.GetString(pemData[pemFields.Label]);
byte[] keyData = Convert.FromBase64String(Encoding.UTF8.GetString(pemData[pemFields.Base64Data]));

Benefits: Faster, cleaner handling of standard security file formats.

Numeric String Comparison

Earlier, strings sorted lexically, so "File10" came before "File2". Now, natural numeric ordering is built-in.

var versions = new[] { "File1", "File10", "File2" };
Array.Sort(versions, StringComparer.Create(CultureInfo.InvariantCulture, CompareOptions.NumericString));

Console.WriteLine(string.Join(", ", versions)); // File1, File2, File10

Benefits: Sorting UI lists, filenames, and version numbers.

TimeSpan.FromMilliseconds Overloads

Earlier, Ambiguity with LINQ and long arrays. Now, cleaner LINQ integration.

long[] delays = { 200, 400, 800 };
var spans = delays.Select(TimeSpan.FromMilliseconds);

foreach (var span in spans)
    Console.WriteLine(span);

Benefits: Simplifies time-related functional code.

OrderedDictionary Enhancements

Earlier, limited index handling APIs. Now, you can update values directly using index-aware methods.

var counts = new OrderedDictionary<string, int>();
if (!counts.TryAdd("bananas", 1, out int idx))
{
    counts.SetAt(idx, counts.GetAt(idx).Value + 1);
}
Console.WriteLine(counts.GetAt(0));

Benefits: Frequency tracking, ordered logs, quick updates.

ReferenceHandler Support in JSON Source Generators

Earlier, serializing object graphs with cycles caused stack overflows. Now, the Preserve option supports circular references.

public class Category
{
    public string Name { get; set; }
    public Category? Parent { get; set; }
}
[JsonSourceGenerationOptions(ReferenceHandler = JsonKnownReferenceHandler.Preserve)]
[JsonSerializable(typeof(Category))]
internal partial class JsonCtx : JsonSerializerContext { }
var node = new Category { Name = "Root" };
node.Parent = node;
string output = JsonSerializer.Serialize(node, JsonCtx.Default.Category);
Console.WriteLine(output);

Benefits: Enables safe serialization for complex graphs.

Wrapping Up

The combination of C# 14 and the new base library capabilities in .NET 10 presents a compelling platform for modern developers. With enhancements in API design, runtime performance, and language expressiveness, this release solidifies .NET as a top-tier development framework. I have added one demo project with the article. Please feel free to explore that as well.

Thank You, and Stay Tuned for More!

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More
Previous PostOlder Posts Home