Reputation: 2058
I need to load the content of a file on different computers at the same time. Because a StreamReader will occupy the file, I want to copy it to a temporary folder before opening it. (The title is more general as there should be no difference between two threads running on one computer and two computers running one thread each.)
Question: will two threads copying a file at the same time affect each other even when the copy destinations are separated?
Upvotes: 1
Views: 423
Reputation: 38199
Your operation is reading. It is like reading a book by 2 person simultaneously. So it is thread safe.
However, if you write some note to the file by two threads - it is not thread safe. It is like two person writing some notes in one copybook. They will just disturb each other and letters will be not correct and the meaning will be incorrect.
Upvotes: 1
Reputation: 63772
Don't - it's much easier to just use the correct arguments when creating your file stream.
The key is the FileShare
setting - it says what kinds of operations are allowed on the file you have opened. Specify FileShare.Read
, and any number of concurrent read operations (that also have a FileShare.Read
) on the same file will work just fine.
It's as simple as
File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read)
Upvotes: 2
Reputation: 203825
It's safe to read a file from multiple threads/processes/machines, as long as there is no one writing to the file at the same time.
Upvotes: 3