c# - System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process -
i using next code log errors of web application.
using (streamwriter mystream = new streamwriter(slogfilepath, true)) { mystream.writeline(string.format("{0, -45}{1, -25}{2, -10 {3}", guid, datetime.now, stringenum.getstringvalue(enummsg), stext)); }
sometimes, following exception 'system.io.ioexception: process cannot access file '.txt' because being used process.' thrown.
i think caused multiple instances of web app @ same time. can me fix problem, please ?
edit: have add every method log this:
date - method x started.
date - exception.message (table not found or other errors)
date - method x stopped.
and when error appears, it's logged this:
date - system.io.ioexception: process cannot access file '.txt' because being used process.
sadly windows not allow waiting on file lock. in order around applications have create lock processes involved can check.
the use of code prevent threads within single process accessing file:
/* suitable single process fails multiple processes */ private static object lockobj = new object(); lock (lockobj) { using (streamwriter mystream = new streamwriter(slogfilepath, true)) { mystream.writeline(string.format("{0, -45}{1, -25}{2, -10 {3}", guid, datetime.now, stringenum.getstringvalue(enummsg), stext)); } }
in order lock across multiple processes mutex lock required. gives name lock other processes can check for. works this:
/* suitable multiple processes on same machine fails multiple processes on multiple machines */ using (mutex mymutex = new mutex(true, "some name unlikly clash other mutextes", bool)) { mymutex.waitone(); try { using (streamwriter mystream = new streamwriter(slogfilepath, true)) { mystream.writeline(string.format("{0, -45}{1, -25}{2, -10 {3}", guid, datetime.now, stringenum.getstringvalue(enummsg), stext)); } } { mymutex.releasemutex(); }
}
i don't think mutexes can access remote machines if have file on file share , trying write processes on multiple machines better off writing server component on machine hosts file mediate between processes.
Comments
Post a Comment