Mono BLOG

Blog about Microsoft technologies (.NET, ASP.NET Core, Blazor, EF Core, WPF, TypeScript, etc.)

Improving Thread Communication in .NET: Moving Beyond Flags and Polling

Allen Liu

In multi-threaded development, we often use flags and polling to control execution logic within threads. However, this approach reduces code readability and maintainability while lacking elegance. This article explores how to use semaphores and other mechanisms to replace polling and flags, thereby improving inter-thread communication and control.

Traditional Approach

First, let's examine the traditional approach using flags and polling with a simple example:

class MyService
{
    private volatile bool _shouldStop;
    private Thread? _workerThread;

    public void Start()
  ...
Read full article

Deep Dive into .NET 8 WebApplication: Architecture and Components

Allen Liu

WebApplication is used to configure the HTTP pipeline and routes in web applications. In this article, I'll break down its components and structure.

/// <summary>
/// The web application used to configure the HTTP pipeline, and routes.
/// </summary>
[DebuggerDisplay("{DebuggerToString(),nq}")]
[DebuggerTypeProxy(typeof(WebApplication.WebApplicationDebugView))]
public sealed class WebApplication : IHost, IDisposable, IApplicationBuilder, IEndpointRouteBuilder, IAsyncDisposable

IHost

First and foremost, a web application is a program, and IHost is the abstraction of that p...

Read full article

.NET 8 Dependency Injection

Allen Liu

Dependency Injection (DI) is a design pattern used to decouple dependencies between components (services). It achieves this by delegating the creation and management of dependencies to an external container, rather than having components create their dependent objects directly.

In .NET, this is primarily implemented using IServiceCollection and IServiceProvider, which are now integral parts of the runtime libraries, making them universally available across the .NET platform!

1 ServiceCollection

IServiceCollection is essentially a list of ServiceDescriptor objects. A `ServiceDescr...

Read full article

Three Methods to Copy Directories in C#

Allen Liu

Copying directories in C# isn’t straightforward since .NET lacks a built-in method for this task. This guide explores three practical approaches to achieve directory copying, each with its pros and cons.


Method 1: Recursive Copy

This method recursively copies files and subdirectories. It’s intuitive and aligns with Microsoft’s recommended pattern but requires careful handling of nested folders.

static void CopyDirectory(string sourceFolderPath, string targetFolderPath)
{
    Directory.CreateDirectory(targetFolderPath);

    foreach (string filePath in Directory.GetFiles(so...
Read full article

Configuration Management in .NET Core with appsettings.json

Allen Liu

A comprehensive guide to leveraging appsettings.json for flexible configuration management in .NET Core applications.

Quick Start

1. Create appsettings.json

{
  "AppSettings": {
    "LogLevel": "Warning",
    "ConnectionStrings": {
      "Default": "Server=localhost;Database=mydb;"
    }
  }
}

2. Basic Configuration Loading

using Microsoft.Extensions.Configuration;

var config = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

string logLevel = config["AppSettings:LogLevel"];
string conne...
Read full article

Task in C#

Allen Liu

The Task class in C# is a powerful tool for multithreaded programming, enabling asynchronous operations, parallel processing, and task cancellation. This guide demonstrates common patterns and best practices for leveraging Task effectively.


1. Executing Asynchronous Operations

Use Task.Run to offload work to the thread pool and await to handle completion.

static async Task<int> LongRunningOperationAsync()
{
    await Task.Delay(1000);  // Simulates async work (e.g., I/O)
    return 1;
}

static async Task MyMethodAsync()
{
    int result = await Task.Run(() => Long...
Read full article