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);
私の唯一の問題は、同時実行足すの場合に発生します例外のタイプです。私はすでに物事が違うことを知っています。私はいくつかの注意事項を追加してみましょう:
- はありません、私ははい、私ははい、私が本当にしたいインプロセスの同時実行
- ためのIOC +ミューテックスとの並行性を扱うことのシナリオ
- にNLogを使用したくありませんそれは別のPROCによって使用されているので、「プロセスはファイル 『{0}』にアクセスすることができない
:すべて、テキストと
IOException
であろう同じファイルに
Thxs、! – Mose
私はそれを1分で入れます... – Aliostad
ああ、私は情報の源を意味しました^^しかし、スニペットは興味のあるユーザーにとっても魅力的です(私のものは長すぎました) – Mose