Is File.ReadAllText Safe?

In particular, a thread will be created using TPL Task.Factory.StartNew :

 Task.Factory.StartNew(() => { File.ReadAllText(@"thisFile.txt"); }); 

Causes any problems, etc.? Apparently no thread safety is mentioned in the MSDN resource

This is in a SOAP web service environment.

Ps Please, I do not want to know about the advantages and disadvantages of using Tasks in a web environment. I am fully aware of these issues, please just take it for granted that in my case this model is justified, thanks.

+7
c # file-io web-services task-parallel-library
source share
4 answers

This is great - if you are not writing anything to the file at the same time, in this case you will not be able to open the file (or you may see a partial record).

According to the File documentation :

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members do not guarantee thread safety.

(Not that there can be any instance methods, since this is a static class ...)

+12
source share

Yes, this alone will be thread safe; however, it still obeys the usual rules of the file system: simultaneous access to a single file depends on which flags were used by competing descriptors. If any descriptor is marked for exclusive access, then it will exit with an IO exception.

+7
source share

In fact, there is no such thing as thread safety without determining which operations are used.

If all threads (and processes!) Just read the file anyway, reading is safe. If, however, some streams (or other processes) are written to a file, you can get the semi-task information, you never know how the recording is organized.

For more failsafe access, you can use

 using (var s = new FileStream(..., FileMode.Open, FileAccess.Read, FileShare.None)) using (var tr = new StreamReader(s)) { content = tr.ReadToEnd(); } 

The documentation for File.ReadAllText says nothing and, therefore, nothing guarantees locking.

+1
source share

Here is a path similar to what Vlad suggested. I use the FileShare Read option, so other threads can read from the same file.

 byte[] buffer; using (FileStream fs = new FileStream("pathGoesHere", FileMode.Open, FileAccess.Read, FileShare.Read)) { buffer = new byte[fs.Length]; fs.Read(buffer, 0, (int)fs.Length); } 
0
source share

All Articles