2010-12-01 27 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

相關問題