lucenenet-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Van Den Berghe, Vincent" <Vincent.VanDenBer...@bvdinfo.com>
Subject CreateTempFile is not thread-safe
Date Mon, 02 Jan 2017 08:37:44 GMT
Hello,

Creating AnalyzingSuggester in parallel sometimes fails with an IOException "The file is already
used by another process".
This is due to a flaw in FileSupport.CreateTempFile, most notably this:

                    if (File.Exists(fileName))
                    {
                        attempt++;
                        continue;
                    }
                    // Create the file
                    File.WriteAllText(fileName, string.Empty, new UTF8Encoding(false) /* No
BOM */);


If 2 or more threads execute File.Exists very close one after another, and the file isn't
found, the first call to File.WriteAllText will succeed and the other ones will succeed as
well since an existing file is simply overwritten.
Dependent code will attempt to use the file as if it were unique, which will then trigger
the exception mentioned above. Yes, it happens!
Consider replacing the File.WriteAllText call (which just creates an empty file) with:

                           using (new FileStream(fileName, FileMode.CreateNew))
                           {
                                  // do nothing
                           }

... which will fail if the file doesn't exist, and the exception will trigger another attempt.
 This will work better as intended.


Happy new year,

Vincent Van Den Berghe


Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message