Assume we have 3 processes, they write to a specific file by order, in some cases when a process wants to write to the file the process closed (In middle of Writing), so access to file for another 2 processes is in trouble, I add a server process that control order of processes and when a process closed there is an event raised, so how can I release sources (file access) in this event when a process closed. Something like File.Release(FilePath);
Edit:
Write to File as Following:
try {
if(!File.Exists(FilePath))
throw new Exception("File does not Exist.");
bool Clear = false;
using(StreamReader sr = new StreamReader(FilePath)) {
if(sr.ReadToEnd().Length > 1200)
Clear = true;
}
if(Clear)
using(StreamWriter sw = new StreamWriter(FilePath, false)) {
sw.WriteLine(Text);
sw.Flush();
} else
using(StreamWriter sw = new StreamWriter(FilePath, true)) {
sw.WriteLine(Text);
sw.Flush();
}
} catch(Exception ex) {}
This is the example type we meant when saying use , keyword “using”. Never close the streamwriter explicitly nor dispose it explicitly. using does all the magic for you. It disposes when the work is done and when you go out of this using block.
In a multi-threaded environment if you use close or dispose explicitly, the threads will have problem considering that the thread may just try to open the object while the previous thread just disposed it. you will have problems synchronizing your threads. This is the same problem that is normally faced in server applications which has multiple connections running into database. That’s the reason we need to use it like this with Idisposable.
C# USING keyword – when and when not to use it?
This explains more about it.
Update: multiple clients writing at the same time to a single file is your problem. As said by the people above, no two process can get hold of the same file at the same time in write mode. Either it has to wait if you write large data, this time of waiting is significantly noticeable or you can collect the objects from the clients, queue them and write them actually from the server. Giving write access on a file that is on the server to the client can also be avoided. If your data is serialized , the you could use google protocol buffers for passing the data.
If you are handling the file from the client and if the client process is terminated mid-way, there will be no write handle to the file now and obviously it will be free for another process to acquire a handle on it with write access.