views:

89

answers:

3

I've got a method which performs a delete and create file. there are issues with the threads all trying to access the file at the same time.

How can i limit access to the file?

public static Save(string file)
{
  //1.Perform Delete
  //2.Perform Write 
}

Note that the method is static so is it possible to lock the process within the static method?

Cheers

+4  A: 
private static readonly object _syncRoot = new object();
public static void Save(string file)
{
    lock(_syncRoot) {
        //1.Perform Delete
        //2.Perform Write 
    }
}

Or you could use the MethodImplAttribute which puts a lock around the whole method body:

[MethodImpl(MethodImplOptions.Synchronized)]
public static void Save(string file)
{
    //1.Perform Delete
    //2.Perform Write 
}
Darin Dimitrov
Beat me to it! The only thing I would do different is declare _syncRoot as readonly.
RichardOD
+1 for MethodImplAttribute
Anwar Chandra
@RichardOD, as you suggested I've added `readonly`.
Darin Dimitrov
While this suggestion will work, it potentially introduces a lot of contention into a website. It is probably worth pointing this out in the answer, as if every single request to a page results in this being called, performance will suffer.
Rob Levine
What will happen if the method threw an exception, will the lock automatically release?
@Wololo, the lock construct is analogous to `Monitor.Enter(lockObj); try { /* code */ } finally { Monitor.Exit(lockObj) }`, so this should pretty much answer your question.
Darin Dimitrov
A: 

You will have to use a lock on a static object.

private static Object saveLock = new Object();

public static Save(string file)
{
   lock (saveLock )
   {
     //...
   }
}
Matthieu
A: 

Have a look at this thread which discusses the use of the lock statement.

pmarflee