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.
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...)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With