Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to write to a file, but may have potentially multiple writers at once, need to lock

In a asp.net web application, I want to write to a file. This function will first get data from the database, and then write out the flat file.

What can I do to make sure only 1 write occurs, and once the write occurrs, the other threads that maybe want to write to the file don't since the write took place.

I want to have this write done ONLY if it hasn't been done in say 15 minutes.

I know there is a lock keyword, so should I wrap everything in a lock, then check if it has been updated in 15 minutes or more, or visa versa?

Update

Workflow:

Since this is a web application, the multiple instances will be people viewing a particular web page. I could use the build in cache system, but if asp.net recycles it will be expensive to rebuild the cache so I just want to write it out to a flat file. My other option would be just to create a windows service, but that is more work to manage that I want.

like image 439
public static Avatar asked Sep 18 '08 15:09

public static


3 Answers

Synchronize your writing code to lock on a shared object so that only one thread gets inside the block. Others wait till the current one exits.

lock(this)
{
  // perform the write.
}

Update: I assumed that you have a shared object. If these are different processes on the same machine, you'd need something like a Named Mutex. Looky here for an example

like image 107
Gishu Avatar answered Oct 19 '22 23:10

Gishu


is it not better to lock an object variable rather than the whole instance?

like image 40
redsquare Avatar answered Oct 19 '22 22:10

redsquare


File I/O operations that write to the file will automatically lock the file. Check if the file is locked (by trying the write) and if it is do not write. Before doing any writes, check the timestamp on the file and see if its more than 15 minutes.

afaik you can not write to a file without it being locked by Windows/whatever.

Now all that's left for you is to look up how to do the above using msdn (sorry, I can't be bothered to look it all up and I don't remember the C# classes very well). :)

like image 25
jheriko Avatar answered Oct 19 '22 22:10

jheriko