Solving Concurrency Problems with Distributed Locks

Locks in Single-Process Applications In a single-machine environment, we can use thread locks to solve concurrency problems. In a distributed system, however, thread locks cannot solve concurrency problems, because a thread lock in a distributed system can only lock the current process, not other processes. In .NET, we can use the lock keyword to implement a thread lock. https://learn.microsoft.com/zh-cn/dotnet/csharp/language-reference/statements/lock private static readonly object _lock = new object(); public void DoSomething() { lock (_lock) { // Business logic } } C# 13 introduces a new thread synchronization type, System.Threading.Lock, which simplifies lock usage through scope management, making the code clearer and more reliable. ...

March 10, 2026

Starting Distributed Microservices with Aspire

Preparing the Database docker run --name postgres -e POSTGRES_PASSWORD=postgres -e TZ=Asia/Shanghai -d -p 5432:5432 postgres docker run --name pgadmin -e PGADMIN_DEFAULT_EMAIL=test@test.com -e PGADMIN_DEFAULT_PASSWORD=test -e TZ=Asia/Shanghai -d -p 5050:80 dpage/pgadmin4 Initializing the Dapr Runtime dapr init -s --from-dir C:\dapr Extending the Wait Time for RabbitMQ Startup public static IResourceBuilder<IDaprSidecarResource> WithReference(this IResourceBuilder<IDaprSidecarResource> builder, IResourceBuilder<IResourceWithConnectionString> resourceBuilder, int waitInSeconds = 10) Updating MediatR Dependency Injection Previously, behaviors were registered with the options.AddBehavior method; now they are registered with the options.AddOpenBehavior method. builder.Services.AddMediatR(options => { options.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); options.AddOpenBehavior(typeof(LoggingBehavior<,>)); options.AddOpenBehavior(typeof(ValidatorBehavior<,>)); options.AddOpenBehavior(typeof(TransactionBehavior<,>)); }); Microservices Using Distributed Events Need the HttpContext Injected builder.Services.AddHttpContextAccessor(); Dropping a Database in Azure Data Studio -- Terminate all sessions connected to the target database SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'my_database' AND pid <> pg_backend_pid(); -- Drop the database DROP DATABASE my_database; Automatically Creating the Database Before IdentityService Demo Data Generation await serviceProvider.GetRequiredService<IdentityServiceDbContext>().Database.EnsureCreatedAsync(cancellationToken); Consistently Use DateTimeOffset Instead of DateTime The advantage of using UTC time is that it can be converted between time zones without losing time information, which helps programs handle time better and benefits the internationalization and localization of cross-time-zone applications. ...

March 10, 2026

Storing Data in a PostgreSQL Database

Starting a PostgreSQL Database in Docker https://www.postgresql.org docker pull postgres docker run --name postgres -e POSTGRES_PASSWORD=postgres -e TZ=Asia/Shanghai -d -p 5432:5432 postgres Connecting to the PostgreSQL Database with PgAdmin https://www.pgadmin.org SHOW timezone; Using the PostgreSQL Database with EF Core dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL Defining the Entity Type public class User { public int Id { get; set; } public string UserName { get; set; } public string PasswordHash { get; set; } public DateTimeOffset CreationTime { get; set; } = DateTimeOffset.UtcNow; } Configuring the Entity Type public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.ToTable("Users"); builder.HasKey(x => x.Id); builder.Property(x => x.UserName).IsRequired().HasMaxLength(50); builder.Property(x => x.PasswordHash).IsRequired().HasMaxLength(50); builder.Property(x => x.CreationTime); } } Creating the DbContext public class IdentityServiceDbContext : DbContext { public IdentityServiceDbContext(DbContextOptions<IdentityServiceDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true); AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true); } } Database Connection String { "ConnectionStrings": { "IdentityDatabase": "Host=localhost;Port=5432;Database=IdentityService;Username=postgres;Password=postgres" } } Registering the DbContext builder.Services.AddDbContext<IdentityServiceDbContext>(options => { options.UseNpgsql(builder.Configuration.GetConnectionString("IdentityDatabase")); }); Migrating the Database dotnet tool install --global dotnet-ef dotnet add package Microsoft.EntityFrameworkCore.Design dotnet ef migrations add InitialCreate --output-dir EntityFrameworks/Migrations dotnet ef database update PostgreSQL Database Naming Conventions https://github.com/efcore/EFCore.NamingConventions ...

March 10, 2026

Testing in the Zero Framework

Automated testing is an excellent way to make sure application code does what its author intends. The Zero Framework provides unit tests, integration tests, and load tests. Testing frameworks on the .NET platform include xUnit, NUnit, and MSTest, with xUnit being the most widely used. Whichever testing framework you use, tests can be run from the command line or from an IDE. Unit Tests A unit test is a test that exercises an individual software component or method, also known as the “unit of work.” Unit tests should only test code within the developer’s control; they do not test infrastructure concerns. Infrastructure concerns include interactions with databases, file systems, and network resources. Unit tests in the Zero Framework use the xUnit framework. ...

March 10, 2026

Updating from .NET 8.0 to .NET 9.0

Update Visual Studio to the Latest Preview Download and install the Visual Studio preview, and install the .NET 9.0 SDK. Update the Project File Open the project file and change <TargetFramework>net8.0</TargetFramework> to <TargetFramework>net9.0</TargetFramework>. Update NuGet Packages Open the NuGet package manager and update all NuGet packages to the latest version. Update the Aspire and MAUI Workloads Open the Aspire workload and update all Aspire packages to the latest version. dotnet workload install aspire android ios maccatalyst maui-android maui-desktop maui-mobile maui-windows To Add Tab Autocompletion to PowerShell for the .NET CLI https://learn.microsoft.com/zh-cn/dotnet/core/tools/enable-tab-autocomplete

March 10, 2026

Upgrade Projects with .NET Upgrade Assistant

What is .NET Upgrade Assistant? .NET Upgrade Assistant is a tool that helps migrate legacy projects to newer .NET versions. It can help you: Identify dependencies and API usage. Recommend an appropriate .NET target framework. Apply or suggest code changes required for migration. Use .NET Upgrade Assistant in Visual Studio You can install the .NET Upgrade Assistant extension in Visual Studio. Use .NET Upgrade Assistant from the command line Install the CLI tool: ...

March 10, 2026

Upgrading the Zero Framework to Aspire 13.0

Simplified Solution File Format From sln to slnx: the new slnx format is easier to read and maintain, removes redundant information, and makes the project structure clearer. dotnet sln migrate Also update the sln files referenced in slnf files to slnx files. Upgrading the Target Framework to .NET 10 In the project files, change the target framework from net9.0 to net10.0: <TargetFramework>net10.0</TargetFramework> Upgrading Aspire to 13.0.0 In the project files, update the Aspire package version to 13.0.0 ...

March 10, 2026

Upgrading the Zero Framework to Aspire 9.0

Upgrading the Visual Studio Development Tools Use Visual Studio Installer to upgrade. After upgrading to v17.12, the .NET 9.0 SDK and the Aspire 9.0 workload are installed automatically. Non-Visual Studio Development Environments Install .NET Core SDK 9.0 Install the latest .NET SDK 9.0 release Check the .NET SDK version: dotnet --version dotnet --list-sdks Upgrade the Aspire Workload Run the following commands in the project directory: dotnet workload uninstall aspire dotnet workload install aspire dotnet workload list dotnet workload update Upgrading the Project Files Add the new node to the Host project: ...

March 10, 2026

User Interfaces and Design Languages

User Experience User Experience (UX) refers to how users feel when using a product. It is a comprehensive concept that includes users’ perceptions, emotions, attitudes, and moods toward the product. User Experience Design (UXD) is a user-centered design methodology aimed at increasing user satisfaction and improving users’ understanding and use of the product. Factors such as color, typography, layout, and interaction all affect user experience. Therefore, user experience must be considered when designing user interfaces, providing a clean, intuitive, and easy-to-use interface to improve user satisfaction. ...

March 10, 2026

Using .HTTP files in Visual Studio 2022

Comment Lines starting with # or // are comments and are ignored when Visual Studio sends an HTTP request. variable Lines starting with @ define variables using the syntax @VariableName=Value. @hostname=localhost @port=44320 GET https://{{hostname}}:{{port}}/weatherforecast multiple requests The request format is: [<HTTP-verb>] <url> [<HTTP-version>] [<request-headers>] [<request-body>] GET https://localhost:7220/weatherforecast ### GET https://localhost:7220/weatherforecast?date=2023-05-11&location=98006 ### GET https://localhost:7220/weatherforecast HTTP/3 ### Request headers GET https://localhost:7220/weatherforecast Date: Wed, 27 Apr 2023 07:28:00 GMT ### GET https://localhost:7220/weatherforecast Cache-Control: max-age=604800 Age: 100 ### request body POST https://localhost:7220/weatherforecast Content-Type: application/json { "date": "2023-05-11", "location": "98006" } Create an HTTP file using a template Right-click the ASP.NET Core project Add > New Item ASP.NET Core>General Select HTTP File, then select Add Use the Endpoint Explorer View > Other Windows > Endpoint Resource Management

March 10, 2026