Master essential advanced programming concepts that every developer should know.
1. Dependency Injection (DI)
Definition: A design pattern where objects receive their dependencies from external sources rather than creating them internally.
Without DI
public class UserService
{
private Database _db = new Database(); // Tight coupling
public User GetUser(int id)
{
return _db.Query(id);
}
}
With DI
public class UserService
{
private readonly IDatabase _db;
// Dependency injected via constructor
public UserService(IDatabase database)
{
_db = database;
}
public User GetUser(int id)
{
return _db.Query(id);
}
}
Benefits: Testability, loose coupling, easier maintenance
2. Mutex (Mutual Exclusion)
Definition: A synchronization primitive that prevents multiple threads from accessing a shared resource simultaneously.
private static Mutex mutex = new Mutex();
public void AccessSharedResource()
{
mutex.WaitOne(); // Acquire lock
try
{
// Critical section - only one thread at a time
Console.WriteLine("Accessing shared resource");
Thread.Sleep(1000);
}
finally
{
mutex.ReleaseMutex(); // Release lock
}
}
3. Lock
Definition: A lightweight synchronization mechanism in C# for thread-safe access to shared resources.
private static object lockObject = new object();
private static int counter = 0;
public void IncrementCounter()
{
lock (lockObject)
{
counter++; // Thread-safe increment
Console.WriteLine($"Counter: {counter}");
}
}
Difference: Mutex can work across processes, Lock only within the same process
4. Watchdog
Definition: A monitoring mechanism that detects and recovers from system failures or hangs.
public class Watchdog
{
private Timer _timer;
private DateTime _lastHeartbeat;
public void Start()
{
_lastHeartbeat = DateTime.Now;
_timer = new Timer(CheckHeartbeat, null, 0, 5000); // Check every 5s
}
private void CheckHeartbeat(object state)
{
if ((DateTime.Now - _lastHeartbeat).TotalSeconds > 10)
{
Console.WriteLine("System hang detected! Restarting...");
RestartSystem();
}
}
public void Heartbeat()
{
_lastHeartbeat = DateTime.Now; // Reset watchdog
}
}
5. CancellationToken
Definition: A mechanism to signal cancellation of asynchronous operations.
public async Task LongRunningOperation(CancellationToken token)
{
for (int i = 0; i < 100; i++)
{
token.ThrowIfCancellationRequested(); // Check for cancellation
await Task.Delay(100);
Console.WriteLine($"Progress: {i}%");
}
}
// Usage
var cts = new CancellationTokenSource();
var task = LongRunningOperation(cts.Token);
// Cancel after 2 seconds
await Task.Delay(2000);
cts.Cancel(); // Triggers cancellation
6. Scaffolding
Definition: Automatic code generation based on templates to create boilerplate code quickly.
# ASP.NET Core scaffolding example
dotnet aspnet-codegenerator controller -name ProductController -m Product -dc AppDbContext --relativeFolderPath Controllers --useDefaultLayout
# Generates:
# - ProductController.cs with CRUD actions
# - Views (Index, Create, Edit, Delete, Details)
# - Routes and model binding
Benefits: Faster development, consistency, reduced errors
Comparison Table
| Concept | Purpose | Use Case |
|---|---|---|
| Dependency Injection | Loose coupling | Testable, maintainable code |
| Mutex | Cross-process synchronization | Shared resources across processes |
| Lock | Thread synchronization | Thread-safe operations |
| Watchdog | System monitoring | Detect and recover from hangs |
| CancellationToken | Async cancellation | Stop long-running operations |
| Scaffolding | Code generation | Rapid development |