2010-12-01 6 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); 
    

    내 유일한 질문은 동시성의 writting의 경우에 발생합니다 예외의 유형입니다. 나는 이미 일이 다르게 행해질 수 있다는 것을 알고 있습니다. 내가 몇 가지 고려 사항 추가하자

    • 아니오, 나는
    • 예 내가
    • 예 내가 정말 원하는에서 프로세스 동시성에 대한 IOC + 뮤텍스와 동시성을 처리하는 시나리오에서 NLog를 사용하지 않으려는 모든 로그가 동일한 파일에 기록되는 것은
  • 답변

    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

    +0

    그래! 나는 1 분 안에 그것을 올려 놓을 것이다 ... – Aliostad

    +0

    오, 나는 정보의 원천을 의미했다. ^^ 그러나 스 니펫은 관심있는 사용자들에게 너무 멋지다. (내 것이 너무 길다) – Mose