Skip to main content

Posts

Showing posts from October, 2025

Finalize vs Dispose in C# — The Subtle Art of Cleaning Up

Hello, .NET enthusiasts! 👋 Have you ever noticed how some objects seem to clean themselves up, while others require your explicit call to Dispose() ? Or perhaps you’ve seen the mysterious ~ClassName() syntax and wondered if it’s the same as Dispose ? Welcome to one of C#’s most overlooked yet crucial topics — understanding the difference between Finalize and Dispose . 1) Why Cleanup Even Matters Every application allocates memory, file handles, network connections, or database resources during its lifetime. Managed objects in .NET are automatically cleaned up by the Garbage Collector (GC) , but unmanaged resources — like file streams, sockets, or database connections — don’t play by GC’s rules. That’s when we, as developers, must step in and guide .NET on how to tidy up properly. In short: Finalize is the system’s fallback janitor, and Dispose is your personal cleanup plan. 2) Meet Finalize — The Automatic Cleanup The Finalize() method, also know...

Master the Volatile Keyword in C# — When Threads Compete for Memory

Hello, .NET enthusiasts! 👋 Have you ever encountered that mysterious bug where your background thread refuses to stop even after setting a flag to false? You pause, debug, and realize—no exception, no logic error—just a stubborn loop running forever. Welcome to the world of thread visibility . And the quiet hero behind fixing it? The volatile keyword. 1) The Mystery of Memory Visibility When your application runs on multiple threads, every CPU core may maintain its own little “cache” of variables. A thread could read a copy of a value that’s slightly outdated, while another thread has already updated it in main memory. The compiler and CPU do this for performance — but it can break logic that relies on real-time values. This is where volatile steps in. It’s like telling the compiler, “Hey, don’t optimize this one — always fetch the latest value from main memory.” In simpler terms, volatile ensures every read reflects the current truth, not a cached illusion....