简体   繁体   中英

how can my .NET app prevent other processes from writing to a file while my app reads it?

I want my .NET app to read a file that was written to by a Julia app. While reading it, I want my app to somehow lock the file so the Julia process cannot write it while .NET is reading it.

Only the Julia process ever writes this file.
Only my .NET app ever reads this file.

How is this done?

I would like to use:
System.IO.File.Copy( source_filename, destin_filename )

All modern Filesystems work like Databases. As such they have Locks and Transactions. NTFS is a shining example of this.

You want to aquire a Write Lock on the file in addition to your read lock (or just a ReadWrite Lock). And then just only use the read one. There can be multiple read locks, but only one write lock on any given file. In some cases anyone having a write lock can even exclude anyone else getting a read lock (and vice versa) - it can be nesseary to avoid file inconsistencies during reading. But that goes into deep implementation details.

Of course now the question becomes how well the other programm will deal with someone else locking the file. Technically you are supposed to handle that as any other Exogenous exception , but I am the first to admit that I might have skipped that code (and the retry one if nessesary) in some cases. Or the Multitasking for gracefull handling of a long lock aquisition time.

In either case, it might be best to release your lock ASAP. For such a purpose, it can be adviseable to just read the whole file into memory quickly and then work on the memory copy. How to go about that in .NET depends a lot on the filesize. The x32 Memory Limit and Object Limit are notorious for getting in the way with files in the GiB range.

I think the way to go in this case is to have a .net thread that detects existence of new file from Julia, and then immediately moves it to a different, exclusive path, where it is read and deleted. The Julia app is only writing the file every 5 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM