6.13 — Review and Assessment
Mục tiêu bài học
- Nắm được ý chính của bài và mối liên hệ với module.
- Áp dụng được kiến thức vào bối cảnh CRM/.NET backend.
- Sẵn sàng chuyển sang bài kế tiếp với nền tảng chắc chắn.
Nội dung bài học
6.13.1 — Thực hành
Bài 1: Convert sync service th ành async với CancellationToken
Cho sync service sau, hãy refactor thành async và pass CancellationToken xuyên suốt:
// TRƯỚC — sync, block thread
public class CustomerSyncService
{
private readonly AppDbContext _db;
public Customer? GetById(int id)
=> _db.Customers.FirstOrDefault(c => c.Id == id);
public List<Customer> GetAll()
=> _db.Customers.Where(c => c.IsActive).ToList();
public void UpdateLastContact(int id, DateTime contactDate)
{
var customer = _db.Customers.Find(id);
if (customer is null) return;
customer.LastContactDate = contactDate;
_db.SaveChanges();
}
}
Yêu cầu:
- Đổi tất cả method sang
async Task<T> - Dùng
FirstOrDefaultAsync,ToListAsync,FindAsync,SaveChangesAsync - Thêm
CancellationToken ct = defaultvào mỗi method - Viết unit test mock
DbContextđể kiểm tra cancel behavior