2010-12-01 20 views
3

我找到了post talking about handling concurrent file access with StreamWriter在使用StreamReader进行并发文件访问的情况下引发异常

问题是,答案不管理正在访问文件但多个进程的场景。

让我们告诉它不久:

  • 我有多个应用程序
  • 我需要在数据库中集中记录系统
  • 如果数据库失败,我需要一个文件系统日志
备用

有一个已知的并发场景,其中多个应用程序(进程)将尝试在该文件中写入。 这可以通过在短暂延迟后重新尝试写入来进行管理。 但是我不想重新尝试,如果它是安全错误或文件名语法错误。

的代码是在这里:

// true if an access error occured 
bool accessError = false; 
// number fo writing attemps 
int attempts = 0; 

do 
{ 
    try 
    { 
     // open the file 
     using (StreamWriter file = new StreamWriter(filename, true)) 
     { 
      // write the 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) 
    { 
     // WHAT EXCEPTION SHOULD I CATCH HERE ? 
     // sleep before retrying 
     Thread.Sleep(ConcurrentWriteDelay); 
    } 
    finally 
    { 
     attempts++; 
    } 
    // while the number of attemps has not been reached 
} while ((attempts < ConcurrentWriteAttempts) 
      // while we have no access error 
      && !accessError 
      // while the log is not written 
      && !result); 

我唯一的问题是将在并发书面方式的情况下引发的异常的类型。我已经知道事情可以做不同的事情。让我补充几个方面的考虑:

  • 不,我不希望在场景中使用NLOG
  • 是我处理并发与IOC +互斥的进程并发
  • 是的,我真的想在同一个文件被写入所有日志

回答

2

这将是一个IOException文本:

“该进程无法访问文件‘{0}’,因为它是被另一个PROC ESS“。

这是一个简单的方法:

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 the line 
        file.WriteLine(log); 
        // success 
        result = true; 
       } 
      } 
      catch (IOException ioException) 
      { 
       Thread.Sleep(DELAY_MS); 
       retry++; 
      } 
      catch (Exception e) 
      { 

       keepRetry = false; 
      } 

     } 
     return result; 
    } 
+0

Thxs的答案,在你的源很感兴趣! – Mose 2010-12-01 13:28:17

相关问题