c# - Raised exception in the case of concurrent file access with StreamReader -
i found post talking handling concurrent file access streamwriter.
the problem answers not manage scenario file being accessed multiple processes.
let's tell shortly :
- i have multiple applications
- i need centralised logging system in database
- if database fail, need fallback on file system log
there known concurrency scenario, multiple applications (processes) try write in file. can managed re-attempt writing after short delay. don't want ot reattempt if it's security error or filename syntax error.
the code here :
// true if access error occured bool accesserror = false; // number fo writing attemps int attempts = 0; { try { // open file using (streamwriter file = new streamwriter(filename, true)) { // write line file.writeline(log); // success result = true; } } /////////////// access errors /////////////// catch (argumentexception) { accesserror = true; } catch (directorynotfoundexception) { accesserror = true; } catch (pathtoolongexception) { accesserror = true; } catch (securityexception) { accesserror = true; } /////////////// concurrent writing errors /////////////// catch (exception) { // exception should catch here ? // sleep before retrying thread.sleep(concurrentwritedelay); } { attempts++; } // while number of attemps has not been reached } while ((attempts < concurrentwriteattempts) // while have no access error && !accesserror // while log not written && !result);
my question the type of exception raised in case of concurrency writting. know things can done differently. let me add few considerations :
- no, don't want use nlog in scenario
- yes handle concurrency ioc + mutex in-process concurrency
- yes want log written in same file
it ioexception
text:
"the process cannot access file '{0}' because being used process."
this simplistic approach:
static bool logerror(string filename, string log) { const int max_retry = 10; const int delay_ms = 1000; // 1 second bool result = false; int retry = 0; bool keepretry = true; while (keepretry && !result && retry < max_retry ) { try { using (streamwriter file = new streamwriter(filename, true)) { // write line file.writeline(log); // success result = true; } } catch (ioexception ioexception) { thread.sleep(delay_ms); retry++; } catch (exception e) { keepretry = false; } } return result; }
Comments
Post a Comment