"thread safe logging class implementation" Code Answer


i'm going to take a completely different approach here than the other answers and assume you actually want to learn how to write better thread-aware code, and are not looking for 3rd party suggestions from us (even though you may actually end up using one.)

as others have said, you are creating a thread safe textwriter which means calls to writeline are thread-safe, that doesn't mean that a bunch of calls to writeline are going to be performed as an atomic operation. by that i mean there is no guarantee that the four writeline calls are going to happen in sequence. you may have a thread-safe textwriter, but you don't have a thread-safe logger.log method ;) why? because at any point during those four calls, another thread might decide to call log also. this means your writeline calls will be out of sync. the way to fix this is by using a lock statement like so:

private static readonly object _syncobject = new object();

public static void log(string logmessage, textwriter w)    {
   // only one thread can own this lock, so other threads
   // entering this method will wait here until lock is
   // available.
   lock(_syncobject) {
      w.writeline("{0} {1}", datetime.now.tolongtimestring(),
      w.writeline("  :");
      w.writeline("  :{0}", logmessage);
      // update the underlying file.

so, now you have a thread-safe textwriter and a thread-safe logger.

make sense?

By Krishna shidnekoppa on August 7 2022

Answers related to “thread safe logging class implementation”

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