"how to make a class thread safe [closed]" Code Answer

3

in c#, any object can be used to protect a "critical section", or in other words, code that must not be executed by two threads at the same time.

for example, the following will synchronize access to the sharedlogger.write method, so only a single thread is logging a message at any given time.



    public class sharedlogger : ilogger
    {
       public static sharedlogger instance = new sharedlogger();
       
       public void write(string s)
       {
          lock (_lock)
          {
             _writer.write(s);
          }
       }
    
       private sharedlogger() 
       { 
          _writer = new logwriter();
       }
       
       private object _lock = new object();
       private logwriter _writer;
    }

By soshika on August 29 2022

Answers related to “how to make a class thread safe [closed]”

Only authorized users can answer the Search term. Please sign in first, or register a free account.