Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Build, Rebuild, Clean trong Visual Studio: Nên dùng cái nào khi nào?

So sánh 3 chế độ

Chế độHành độngKhi nào dùng
BuildIncremental build: chỉ compile file thay đổiPhát triển hàng ngày (F5, Ctrl+Shift+B)
RebuildClean + Build: xóa tất cả output, build từ đầuSau khi pull code, đổi config, build lỗi lạ, CI/CD
CleanXóa thư mục bin/obj (output)Trước khi zip source, commit, fix cache lỗi

Chi tiết từng lệnh

Build Solution (Ctrl+Shift+B)

  • Kiểm tra timestamp file source vs output.
  • Chỉ biên dịch project/file có thay đổi.
  • Giữ lại assembly của project không thay đổi.
  • Nhanh nhất cho vòng lặp code-build-test.

Rebuild Solution

  • Tương đương: Clean → Build cho từng project theo dependency order.
  • Xóa tất cả file trong bin/ và obj/.
  • Biên dịch lại mọi thứ từ đầu.
  • Dùng khi: Build báo thành công nhưng runtime lỗi, reference bị lệch, sau merge conflict.

Clean Solution

  • Chỉ xóa output (bin/obj), KHÔNG build lại.
  • Dùng khi: Muốn xóa artifact cũ, chuẩn bị package source code, giải phóng disk space.
  • Không làm sạch: package cache NuGet, user files, generated files ngoài bin/obj.

Mối quan hệ

Rebuild = Clean + Build (per project, in dependency order)

Command Line (MSBuild / dotnet CLI)


# Build incremental
dotnet build

# Rebuild (clean + build)
dotnet build --no-incremental
# Hoặc
dotnet clean && dotnet build

# Clean only
dotnet clean

# MSBuild trực tiếp
msbuild MySolution.sln /t:Build
msbuild MySolution.sln /t:Rebuild
msbuild MySolution.sln /t:Clean

Khi nào bắt buộc Rebuild?

  • Thay đổi target framework hoặc NuGet package version.
  • Sửa file .csproj, Directory.Build.props, global.json.
  • Thêm/xóa file source (đôi khi Build không nhận diện).
  • Build thành công nhưng runtime lỗi MissingMethodException, TypeLoadException.
  • Sau khi git pull / git checkout branch khác.
  • Triển khai CI/CD (luôn clean build).

Visual Studio Settings

  • Tools → Options → Projects and Solutions → Build and Run:
  • "On Run, when projects are out of date": Always build (khuyến nghị).
  • "Show Output window when build starts": Check.
  • "Maximum number of parallel project builds": Số core CPU.

Troubleshooting Build Issues

  1. Clean → Rebuild (Fix 90% vấn đề cache).
  2. Xóa thủ công thư mục bin, obj ở root solution.
  3. Xóa .vs folder (hidden) - chứa cache IntelliSense, build.
  4. dotnet nuget locals all --clear - clear NuGet cache.
  5. Restart Visual Studio (giải phóng file lock).

Build Optimization Tips

  • Dùng Project Dependencies đúng để build song song đúng thứ tự.
  • Tách solution lớn thành nhiều solution nhỏ (modular).
  • Dùng dotnet build --no-restore nếu đã restore riêng.
  • Enable Deterministic builds (<Deterministic>true</Deterministic>) cho reproducible artifacts.