c# - Is copying a file while writing to it thread safe? -
is using filestream class write file , .net file.copy method re-create file @ same time thread safe? seems operating scheme should safely handle concurrent access file, cannot find documentation on this. i've written simple application test , seeing weird results. re-create of file showing 2mb, when inspect file content notepad++ it's empty inside. original file contains data.
using system; using system.threading.tasks; using system.threading; using system.io; namespace consoleapplication { class programme { static void main(string[] args) { string filepath = environment.currentdirectory + @"\test.txt"; using (filestream filestream = new filestream(filepath, filemode.create, fileaccess.readwrite)) { task filewritetask = task.run(() => { (int = 0; < 10000000; i++) { filestream.writebyte((byte)i); } }); thread.sleep(50); file.copy(filepath, filepath + ".copy", true); filewritetask.wait(); } } } }
thanks help!
it depends.
depends mean when "thread safe".
first of all, @ constructor:
public filestream(string path, filemode mode, fileaccess access, fileshare share )
notice lastly parameter, states allow other threads , processes file. default applies constructors don't have fileshare.read
, means allow others view file read-only. of course of study unwise if writing it.
that's did, opened file writing, while allowing others read , , "read" includes copying.
also please note, without this: filewritetask.wait();
@ end of code, entire function isn't thread safe, because filestream might closed before start writing.
windows create file access thread safe, in pretty non trivial manner. illustration if have opened file fileshare.none
, have crashed file.copy
, best of knowledge there isn't elegant way .net. general approach windows uses synchronize file access called optimistic concurrency, meaning assume action possible, , fail if isn't.
this question discusses waiting file lock in .net
sharing files between process mutual issue , 1 of ways , inter-process comunication memory mapped files , the msdn documentation
if brave , willing play around winapi , overlapped io, if remember correctly lockfileex allows nice file locking...
also, 1 time there magical thing called transactional ntfs has moved on in realm of microsoft deprecated technologies
c# .net multithreading
No comments:
Post a Comment