TECHNICAL BLOG

Why to use Singleton Design Pattern in c#

A Singleton is a design pattern in C# that ensures a class has only one instance and provides a global point of access to that instance. This is particularly useful when exactly one instance of a class is needed to coordinate actions across a system. In a scenario where multiple parts of an application need to access a file, using the Singleton pattern ensures that the file is accessed by a single instance of a class, preventing potential issues like file locks or data corruption due to concurrent access.

Singleton File Access Class

Using Above FileManager Class..Usage

Here is the console App Output

You can open Log.txt file and find text written on it.

Class Explaination

Thread Safety: We use lock (_lock) to make both file writing and reading thread-safe, ensuring that only one thread can access the file at a time.
Private Constructor: The FileManager constructor is private, so the class can only be instantiated through the GetInstance method.
_filePath: The class takes a file path as a parameter and stores it for future file operations. The FileManager class controls access to the file. All interactions (reading or writing) go through this singleton instance, ensuring there’s only one file access point in the system. Thread safety is achieved by locking both read and write operations, ensuring that only one thread can interact with the file at a time.

Benefits:

Prevents file corruption: By ensuring only one instance of the file handler is used, the Singleton pattern prevents multiple parts of the program from writing to the file simultaneously.
Thread-safe operations: The use of locks makes it safe for multi-threaded environments, ensuring file operations are executed sequentially. This is particularly useful for applications where multiple threads or parts of the application log data to a file (e.g., logging systems, configuration file handlers, etc.).


The perfect choice for Entrepreneur, business advisor and corporates.