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 +互斥的進程併發
- 是的,我真的想在同一個文件被寫入所有日誌
Thxs的答案,在你的源很感興趣! – Mose 2010-12-01 13:28:17