0

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

3 Answers3

6
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
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Beat me to it! The only thing I would do different is declare _syncRoot as readonly. – RichardOD Nov 03 '09 at 09:28
  • 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 Nov 03 '09 at 09:44
  • What will happen if the method threw an exception, will the lock automatically release? –  Nov 03 '09 at 09:50
  • @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 Nov 03 '09 at 09:54
0

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
  • 114
  • 3
0

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

Community
  • 1
  • 1
pmarflee
  • 3,428
  • 20
  • 21