.NET Framework 3.5
ローカルのファイルを使った、ロック処理なんかを実装した訳ですが。
下記のようなソースで、ロックファイルの有無を確認する「if (!file.Exists()) 」のステートメントのExistsメソッド【2】で、最新の状態が返ってこない。
FileInfoオブジェクト(file)をnewしたタイミング【1】の状態の値が返ってきてるっぽい。
これってJavaのFileクラスのExistsメソッドも同じだったっけ???
// ロックファイル FileInfo file = new FileInfo(".lock"); // 【1】ここでオブジェクトができたタイミングのExistsが返ってくる // ロックを確認 int cnt = 0; while (cnt < MAX_CNT) { if (!file.Exists()) // 【2】ここで最新のExistsが返ってこない // if (!File.Exists(file.FullName)) // なのでFileクラスのメソッドを使いましょう { // 同時処理を考慮してfile.Create()の例外をtry-catch(追記:2011/07/01) try { // ロック成功 file.Create(); break; } catch (IOException ioe) { // 同時にロックしに行って、後負け } } // 1000[ms]でMAX_CNT回ループして確認 Thread.Sleep(1000); cnt++; } if (cnt >= MAX_CNT) { // ロック失敗 } // ロックされた処理 … // アンロック if (file.Exists()) // if (!File.Exists(file.FullName)) // ここも念のため { // ロック解除 file.Delete(); }
C#のFileクラスとFileInfoクラス
FileInfo.Exists vs File.Exsists – Solid Syntax
Example 1:
bool fileExists = File.Exist( "myFile.txt" );In example 1, the static method will always query the file system when executed.
(例1では、静的メソッドは、常にファイルシステムを照会します)
Example 2:
FileInfo fileInfo = new FileInfo( "myFile.txt" );
bool fileExists = fileInfo.Exists();In example 2, security checks are only done the first time the FileInfo object is created.
(例2では、セキュリティチェックは、FileInfoオブジェクト作成時に行われます。)
ってことで、逐次確認する場合はFileクラスのExistsメソッド使いましょう。
にしても、Fileクラスはstaticで引数にパス渡さんといかんのが面倒じゃな。。。
せめて、引数にFileInfoオブジェクトが渡せればいいのに。。。