Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is File.ReadAllText thread safe?

Specifically will spawning a thread using the TPL Task.Factory.StartNew:

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

Causing any issues, etc? There doesn't appear to be any mention of thread safety on the MSDN resource

It's in a SOAP web service environment.

Ps Please, I don't want to know about the pro's and cons of using a Task in a web environment. I'm fully aware of these issues, please, just take it for granted that in my case this model is justified, thanks.

like image 983
Liam Avatar asked Nov 14 '13 11:11

Liam


3 Answers

It's fine - assuming nothing's writing to the file at the same time, in which case you may not be able to open the file (or might see partial writes).

As per the documentation of File:

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

(Not that there can be any instance methods, as it's a static class...)

like image 168
Jon Skeet Avatar answered Oct 10 '22 22:10

Jon Skeet


Yes, that will be thread-safe in itself; however, it is still subject to the usual rules of the file-system: concurrent access to the same file depends on which flags were used by the competing handles. If any handle has it marked for exclusive access, then it will fail with an IO-related exception.

like image 10
Marc Gravell Avatar answered Oct 10 '22 22:10

Marc Gravell


There is actually no such thing as "thread safe" without defining what operations are used.

If all the threads (and processes!) are just reading the file in either way, the read is safe. If however some of the threads (or another processes) is writing into the file, you might get a half-up-to-date information, you never know how the writing is organized.

For a more fail-proof access, you could 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 doesn't state anything and therefore doesn't guarantee anything about locking.

like image 2
Vlad Avatar answered Oct 10 '22 23:10

Vlad