c# - How do I make a static class thread-safe? -


i have simple simple logging class static. however, it's not thread safe every call attempts write same file. these exceptions:

the process cannot access file 'logfile.txt' because being used process. @ system.io.__error.winioerror(int32 errorcode, string maybefullpath)  ... 

what best way make thread safe?

public static class logger {     private static readonly string log_filename = "logfile.txt";     private static readonly string log_folder = system.io.path.combine(environment.getfolderpath(environment.specialfolder.applicationdata), "app name");     private static readonly string log_fullpath = system.io.path.combine(environment.getfolderpath(environment.specialfolder.applicationdata), "app name", log_filename);      public static void logmessagetofile(string msg)     {         msg = string.format("{0:g}: {1}{2}", datetime.now, msg, environment.newline);         file.appendalltext(log_fullpath, msg);     } } 

as logging function, able access many different parts of code (hence, why chose static). however, i'm imagining make thread safe, i'll have pass common object lock() on, think defeats purpose of static function. or not case?

public static class logger {     private static readonly string log_filename = "logfile.txt";     private static readonly string log_folder = system.io.path.combine(environment.getfolderpath(environment.specialfolder.applicationdata), "app name");     private static readonly string log_fullpath = system.io.path.combine(environment.getfolderpath(environment.specialfolder.applicationdata), "app name", log_filename);      private static object thelock=new object();      public static void logmessagetofile(string msg)     {         msg = string.format("{0:g}: {1}{2}", datetime.now, msg, environment.newline);         lock (thelock)         {             file.appendalltext(log_fullpath, msg);         }     } } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -